Skip to content

Commit c2c7b75

Browse files
committed
Add description of how to update custom claims on refresh to README
1 parent 674570e commit c2c7b75

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

README.rst

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,9 @@ SLIDING_TOKEN_REFRESH_EXP_CLAIM
276276
Customizing token claims
277277
------------------------
278278

279+
Adding custom claims
280+
~~~~~~~~~~~~~~~~~~~~
281+
279282
If you wish to customize the claims contained in web tokens which are generated
280283
by the ``TokenObtainPairView`` and ``TokenObtainSlidingView`` views, create a
281284
subclass for the desired view as well as a subclass for its corresponding
@@ -309,6 +312,49 @@ for the view, which is in turn used to generate the view's access token.
309312
As with the standard token views, you'll also need to include a url route to
310313
your subclassed view.
311314

315+
Refreshing custom claims
316+
~~~~~~~~~~~~~~~~~~~~~~~~
317+
318+
Certain properties of a token may be updated during the lifetime of a refresh
319+
token. For example, if a user's name is included in the token and the user is
320+
allowed to update their name, access tokens should be updated to reflect these
321+
changes. If you wish to send updated custom token claims with each access
322+
token, which are generated by the ``TokenRefreshView`` and the
323+
``TokenRefreshSlidingView``, create a subclass of the desired view as well as a
324+
subclass of its corresponding serializer. Here's an example of how to customize
325+
the claims in tokens generated by the ``TokenRefreshView``:
326+
327+
.. code-block:: python
328+
329+
from django.utils.six import text_type
330+
from rest_framework_simplejwt.serializers import TokenRefreshSerializer
331+
from rest_framework_simplejwt.views import TokenRefreshView
332+
from rest_framework_simplejwt.tokens import AccessToken
333+
from my_auth_app.models import User # custom user model
334+
335+
class MyTokenRefreshSerializer(TokenRefreshSerializer):
336+
def validate(self, attrs):
337+
# get default access token
338+
data = super().validate(attrs)
339+
access_token_str = data.get('access')
340+
access_token = AccessToken(access_token_str)
341+
342+
# get user for token
343+
user = User.objects.get(pk=access_token['user_id'])
344+
345+
# update custom fields
346+
access_token['name'] = user.name
347+
# ...
348+
349+
data['access'] = text_type(access_token)
350+
return data
351+
352+
class MyTokenRefreshView(TokenRefreshView):
353+
serializer_class = MyTokenRefreshSerializer
354+
355+
As with the standard token views, you'll also need to include a url route to
356+
your subclassed view.
357+
312358
Token types
313359
-----------
314360

0 commit comments

Comments
 (0)