Handle auth workflow with django API and react

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.

since you have set refresh_token as an HTTP-only cookie, it cannot be accessed directly from the frontend. However, your backend should be able to read it from the request.

Possible reasons for the issue:

Cookie Settings: You have httponly=True and secure=False. If your app runs over HTTPS, you need to set secure=True. Also, try changing samesite='Lax' to samesite='None' along with secure=True.

Domain Mismatch: If your backend and frontend run on different domains, you might need to set the cookie with domain="yourdomain.com" in response.set_cookie.

CORS and Cookie Settings: Check your Django settings for SESSION_COOKIE_SAMESITE and CSRF_COOKIE_SAMESITE. Also, ensure that your frontend requests are sent with credentials: "include".

To debug: Check if the refresh_token is actually set in the browser using Developer Tools (Application -> Cookies).

Log request.COOKIES in your backend using print(request.COOKIES) to see if the cookie is being received.

Try these steps and let me know if the issue persists. We can debug further with additional logs

This might help

  1. Make sure your frontend requests include credentials: 'include' eg

    fetch('your refresh token endpoint', { method: 'GET', credentials: 'include' })

  2. Make sure you have CORS parameter set in your settings.py

    CORS_ALLOW_CREDENTIALS = True
    CORS_ALLOWED_ORIGINS = [

    #Add any url u use for your frontend code ] CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = False # make this to True in when u are on prod CSRF_COOKIE_SAMESITE = 'Lax' SESSION_COOKIE_SAMESITE = 'Lax'

3.make sure the frontend contains the CSRF token in the headers if you have any tho.

Also remember if refresh_token cookie is set to httponly=True, Javascript can't read it which is normal. But the browser will send it automatically with requests.

so, Make sure you're calling the refresh endpoint from the browser, not Postman (Postman won’t send cookies) and Use secure=True only if you're on HTTPS; otherwise, it might not work in local.

Вернуться на верх