@@ -276,6 +276,9 @@ SLIDING_TOKEN_REFRESH_EXP_CLAIM
276
276
Customizing token claims
277
277
------------------------
278
278
279
+ Adding custom claims
280
+ ~~~~~~~~~~~~~~~~~~~~
281
+
279
282
If you wish to customize the claims contained in web tokens which are generated
280
283
by the ``TokenObtainPairView `` and ``TokenObtainSlidingView `` views, create a
281
284
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.
309
312
As with the standard token views, you'll also need to include a url route to
310
313
your subclassed view.
311
314
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
+
312
358
Token types
313
359
-----------
314
360
0 commit comments