Search code examples
pythondjangodjango-rest-framework-simplejwt

Django simplejwt: How to add refresh token to dict?


I am using simplejwt to get an access and refresh tokens. In a view I need to create a dict, where the both will be stored as well as access token claims and another additional data. Everything works but by some reason when the refrsh token is added to dict, it returns its decoded value, but not the token.

my views.py


@csrf_exempt
#@api_view(('GET',))
def check_token(request):
    token_refresh = RefreshToken.for_user(request.user)
    print('REFRESH', token_refresh)
    token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
    data = {'token': token, 'refresh_token': token_refresh}

    try:
        valid_data = TokenBackend(algorithm='HS256').decode(token, verify=False)
        data['uui'] = valid_data['user_id']
        data['validUntil'] = valid_data['exp']
        data['clientId'] = 'default'
        print(data)
        return JsonResponse(data)
    except ValidationError as v:
        print("Validation error", v)


print('REFRESH', token_refresh) returns the token:

'REFRESH eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI...'

but data object returns:

{'token': 'eyJ0eXAiOiJKV1QiLCJhbGci...', 'refresh_token': {'token_type': 'refresh', 'exp': 1628664751, 'jti': '38f0e3a4d7bb452681834a6b149aa496', 'user_id': 'None'}, 'uui': 1, 'validUntil': 1628059131, 'clientId': 'default'}

my ideal result:

{'token': 'eyJ0eXAiOiJKV1QiLCJhbGci...', 'refresh_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI...', 'uui': 1, 'validUntil': 1628059131, 'clientId': 'default'}


Solution

  • if you want to create tokens manually for user in djangorestframework-simplejwt you can do this:

    from rest_framework_simplejwt.tokens import RefreshToken
    
    def get_tokens_for_user(user):
        refresh = RefreshToken.for_user(user)
    
        return {
            'refresh': str(refresh),
            'access': str(refresh.access_token),
    
            # Add additional fields here
        }  
    

    now you can use this function in your views.