5
votes

i am trying to verify and decode simple-jwt-django-rest-framework token. I know we can use verify api of simple-jwt. But i want to decode and verify in my views . Below is the current code i am trying:-

//in views.py

class home(APIView):
   def post(self,request,*args,**kwargs):
      print("request is ",request._request)
      verify_token_response = token_verify(request._request)
      print("status_code is ", verify_token_response.status_code)

      if(verify_token_response.status_code == 200):
        jwt_object  = JWTAuthentication() 
        validated_token = jwt_object.get_validated_token(request._request)
        user            = jwt_object.get_user(validated_token)
        print(user)
    
    return Response({
            'status':True, 
            'message':'home'
            })

This code is working for me for token validation. It is validating token correctly , but when i am retrieving the valiated_token and user , it giving me error of :-

{
    "detail": "Given token not valid for any token type",
    "code": "token_not_valid",
    "messages": [
        {
            "token_class": "AccessToken",
            "token_type": "access",
            "message": "Token is invalid or expired"
        }
    ]
}
4
This answer will help for you Decode token and verify userMadhura Prasanna

4 Answers

3
votes

I think you should send the RAW_TOKEN and not request._request

  if(verify_token_response.status_code == 200):
    jwt_object      = JWTAuthentication() 
    header          = jwt_object.get_header(request)
    raw_token       = jwt_object.get_raw_token(header)
    validated_token = jwt_object.get_validated_token(raw_token)
    user            = jwt_object.get_user(validated_token)
    print(user)
3
votes

Basicly any JWT is a result of

  1. Payload
  2. Secret
  3. Encoding algorithm

Payload is just hashmap with user identification, role, permission etc.

payload = {
  username: "James Bond",
  roles: ['admin'],
  permissions: ['user | add', 'user | edit'],
  id: 7,
}

Secret Is a long string like password you have it in your setting.py

SECRET_KEY = config('SECRET_KEY')

Encoding algorithm Is a method for encryption

To decode you must use the same SECRET_KEY used to encode.

import jwt
# Token generated by simple-jwt-django-rest-framework or any
token = "eyJ0eXAiOiJKV1QiL....";
    
print(jwt.decode(token, config('SECRET_KEY'), algorithms=["HS256"]))

You can replace config('SECRET_KEY') with "123" or whatever is in your settings.py

0
votes

When you configure the rest_framework_simplejwt authentication, do you have to configure the SIMPLE_JWT variable on the file settings.py, and there are the ALGORITHM and the SIGNING_KEY how this:

SIMPLE_JWT = {
    ...

    'ALGORITHM': 'HS512',
    'SIGNING_KEY': SECRET_KEY,
    ...
}

Where the SIGNING_KEY are the SECRET_KEYconstant in your settings.py file. Then, do you can get the algorithm value in the ALGORITHM key at SIMPLE_JWT dict. In my case, the algorithm is 'HS512'.

After know the algorithm, do you have to import the SIMPLE_JWT from settings.py and do you can use the decode method from jwt how the example bellow:

import jwt
from your_project.settings import SIMPLE_JWT

...

token = "eyJ0eXAiOiJKV1QiLC..."
jwt.decode(
   token,
   SIMPLE_JWT['SIGNING_KEY'],
   algorithms=[SIMPLE_JWT['ALGORITHM']],
)
0
votes

You can use the JWTAuthentication class from rest_framework_simplejwt.authentication module. it contains a method called authenticate(request) which takes in the request object, checks the validity of the token and returns both the user associated with the token and the validated token with the decoded claims

from rest_framework_simplejwt.authentication import JWTAuthentication
JWT_authenticator = JWTAuthentication()

# authenitcate() verifies and decode the token
# if token is invalid, it raises an exception and returns 401
response = JWT_authenticator.authenticate(request)
if response is not None:
    # unpacking
    user , token = response
    print("this is decoded token claims", token.payload)
else:
    print("no token is provided in the header or the header is missing")