How to set cookie in my custom authentication view( django-rest-framework-simplejwt)?

Viewed 762

After login access and refresh token seted in httponly cookie.So I create CustomAuthentication(Inherit from JWTAuthentication) view to get the httponly cookie.If access token invalid at that time InvalidToken error except(see my below code) then generate new access token by using refresh token.

Question 1 : How to set this access token in cookie?.Here I use Response() but it not work because CustomAuthentication view return user and token instead of response.

Question 2 : Any other recommended way to generate new access token by using refresh token and set in cookie?

Sorry for my English..

authenticate.py:

from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import InvalidToken
from django.conf import settings
import requests
import json
from datetime import timedelta
from .utility import set_browser_cookie
from rest_framework.response import Response

def set_browser_cookie(response,key,value):
    response.set_cookie(
                       key = key, 
                       value = value,
                    #    expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'],
                       secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'],
                       httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'],
                       samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE']
                       )

  

class CustomAuthentication(JWTAuthentication):
    
    def authenticate(self, request):
        header = self.get_header(request)        
        if header is None:
            raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE_ACCESS']) or None
        else:
            raw_token = self.get_raw_token(header)
        if raw_token is None:
            return None
        
        try:
            validated_token = self.get_validated_token(raw_token)
        except InvalidToken:
            refresh = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE_REFRESH'])
            
            if refresh is None:
                return None
                                      
            protocol = 'https' if request.is_secure() else 'http'
            url = f'{protocol}://127.0.0.1:8000/auth/api/token/refresh/'
            data = {"refresh": refresh}
            resp = requests.post(
                url, 
                data=json.dumps(data),
                headers = {'content-type': 'application/json'}
                )
            result = resp.json()
            new_access_token = result['access']
            validated_token = self.get_validated_token(new_access_token)
            
            response = Response()
            set_browser_cookie(response,settings.SIMPLE_JWT['AUTH_COOKIE_ACCESS'],new_access_token)
            
            print("new_tokennnnnnnnn",new_access_token)

        return self.get_user(validated_token), validated_token

Settings.py:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'authentication.authenticate.CustomAuthentication',
    ),
}

Advance thanks..

0 Answers
Related