[Python] handle auth workflow with django API and react

Discussão em 'Python' iniciado por Stack, Fevereiro 20, 2025.

  1. Stack

    Stack Membro Participativo

    I have a frontend app written in react I have a backend application which is a django server. On top of that I am working with a 3rd party True Layer (Open Banking API) The first thing I want to implement is the authentication which I did correctly. However, I am trying to write a method to refresh my access_token thanks to the refresh_token given by the TrueLayer API when user first authenticate.

    The problem is that from what I read online the good practice is to have the refresh_token stored into the HTTP only cookies. So I did something like this

    def truelayer_callback(request):
    code = request.GET.get('code')
    token_data = {
    "grant_type": "authorization_code",
    "client_id": settings.TRUELAYER_CLIENT_ID,
    "client_secret": settings.TRUELAYER_CLIENT_SECRET,
    "redirect_uri": REDIRECT_URI,
    "code": code,
    }
    try:
    data = requests.post(TOKEN_URL, data=token_data).json()
    access_token = data.get('access_token')
    refresh_token = data.get('refresh_token')
    if access_token:
    query_params = urlencode({'token' : access_token})
    response = HttpResponseRedirect(f'{FRONTEND_URL}?{query_params}')
    response.set_cookie(key='refresh_token', value=refresh_token, httponly=True, secure=False, samesite='Lax')
    return response
    return HttpResponseRedirect(f'{FRONTEND_URL}?error=No access token received')
    except Exception as e:
    return HttpResponseRedirect(f'{FRONTEND_URL}?error={str(e)}')


    I set the cookie refresh_token in the response. But in my next method, which is the method called to refresh the access_token when I try to access my refresh_token from cookies I get None:

    def check_refresh_cookie(request):
    refresh_token = request.COOKIES.get("refresh_token") # is None
    token_data = {
    "grant_type": "refresh_token",
    "client_id": settings.TRUELAYER_CLIENT_ID,
    "client_secret": settings.TRUELAYER_CLIENT_SECRET,
    "refresh_token": refresh_token,
    }
    try:
    response = requests.post(TOKEN_URL, data=token_data)
    return JsonResponse({'access_token' : response.json()})
    except Exception as e:
    return HttpResponseRedirect(f'{FRONTEND_URL}?error={str(e)}')


    I am a bit lost right now sure how to proceed to have the refresh token secured and to be able to refresh my access_token

    I didn't include any code from the front because it's basically a button with a onClick method.

    Continue reading...

Compartilhe esta Página