Their official doc only shows implementation for class based views.
How to get this done for a function, ie. Refreshtoken.for_user()?
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),
}
Snippet from here. This only shows how to create token manually.
I know using pyjwt
would make life simpler but there will be another workaround for blacklisting.
The easiest way I always followed is here. You may see that the
Token
class inrest_framework_simplejwt
implemented__setitem__
and__getitem__
. So easily you can add a claim to your token.You have to make a customer serializer that will extend the
TokenObtainSerializer
class. See the code for a better understanding:serializers.py:
And then create a view that will extend the
TokenViewBase
class:views.py
urls.py
Here we go, Done.
After doing those steps and decoding the access token you will find something link this:
For more, you can see this repo. Here I did a project following the
rest_framework_simplejwt
package for learning and understanding the custom authentication backend.