menu

Questions & Answers

Can I return JSON Web Token (JWT) through django-rest-auth login and registration?

I am trying to return JWT from my rest API through django-rest-auth but it gives a different type of token like for eg. 9054f7aa9305e012b3c2300408c3dfdf390fcddf.
I have my own TokenObtainPairSerializer for JWT like this: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): email = user.email token = super(MyTokenObtainPairSerializer, cls).get_token(user) # Add custom claims token['first_name'] = user.first_name token['last_name'] = user.last_name token['email'] = user.email return token
I would like the django-rest-auth to return my custom JWT through the login. Any help will be greatly appreciated.
P.S: I searched through google and other stack-overflow questions, but couldn't find what I'm actually looking for.

Comments:
2023-01-23 00:55:02
Did you try to decode the token? It should have the details you have provided in the token.
2023-01-23 00:55:02
@sonus21 This token provided by django is actually, only for accessing the APIs. What I wanted to implement was, return the JWT instead of the django's built-in token.
2023-01-23 00:55:02
If you have MyTokenObtainPairSerializer and you have JWT then it should work. Did you enable JWT ?
2023-01-23 00:55:02
I was looking for a way to use JWT with the Django-rest-auth and failed. Is there any other options that I can use to return the JWT through Django-rest-auth?
2023-01-23 00:55:02
What did fail? This is a sample to add that.
2023-01-23 00:55:02
I used something like this in settings.py: REST_AUTH = { 'REST_AUTH_TOKEN_MODEL' : 'JWT', 'REST_USE_JWT':True, }
2023-01-23 00:55:02
Answers(1) :

to use JWT with django rest_auth, you'd have to set the following config in the settings.py:

    REST_USE_JWT = True
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [ 
              'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 
        ], 
     }

Also remember to install rest_framework_jwt and add to your INSTALLED_APPS

UPDATE 2023: I use simple jwt these days so an updated version would be:

#---------- REST FRAMEWORK Settings-----------
REST_FRAMEWORK = {
            'DEFAULT_AUTHENTICATION_CLASSES': [ 
               'rest_framework_simplejwt.authentication.JWTAuthentication', 
            ], 
         }