File: customizing_token_claims.rst

package info (click to toggle)
python-djangorestframework-simplejwt 5.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 956 kB
  • sloc: python: 3,783; makefile: 213; javascript: 40; sh: 6
file content (45 lines) | stat: -rw-r--r-- 1,527 bytes parent folder | download | duplicates (2)
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.