1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
.. _customizing_token_claims:
Customizing token claims
========================
If you wish to customize the claims contained in web tokens which are generated
by the ``TokenObtainPairView`` and ``TokenObtainSlidingView`` views, create a
subclass for the desired view as well as a subclass for its corresponding
serializer. Here's an example of how to customize the claims in tokens
generated by the ``TokenObtainPairView``:
.. code-block:: python
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super().get_token(user)
# Add custom claims
token['name'] = user.name
# ...
return token
.. code-block:: python
# Django project settings.py
...
SIMPLE_JWT = {
# It will work instead of the default serializer(TokenObtainPairSerializer).
"TOKEN_OBTAIN_SERIALIZER": "my_app.serializers.MyTokenObtainPairSerializer",
# ...
}
Note that the example above will cause the customized claims to be present in
both refresh *and* access tokens which are generated by the view. This follows
from the fact that the ``get_token`` method above produces the *refresh* token
for the view, which is in turn used to generate the view's access token.
As with the standard token views, you'll also need to include a url route to
your subclassed view.
|