Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode and verify simple-jwt-django-rest-framework token

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"
        }
    ]
}
like image 842
user190549 Avatar asked Jul 13 '20 13:07

user190549


People also ask

What is JWT token in Django REST framework?

Simple JWT provides a JSON Web Token authentication backend for the Django REST Framework. It aims to cover the most common use cases of JWTs by offering a conservative set of default features. It also aims to be easily extensible in case a desired feature is not present.


4 Answers

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

like image 188
BackdoorTech Avatar answered Oct 19 '22 17:10

BackdoorTech


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)
like image 4
Ohad the Lad Avatar answered Oct 19 '22 16:10

Ohad the Lad


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")
like image 4
Mai Elshiashi Avatar answered Oct 19 '22 17:10

Mai Elshiashi


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']],
)
like image 1
Mateus Alves de Oliveira Avatar answered Oct 19 '22 17:10

Mateus Alves de Oliveira