Skip to content

Commit

Permalink
Add description of how to update custom claims on refresh to README
Browse files Browse the repository at this point in the history
  • Loading branch information
henrywoody committed Jan 13, 2019
1 parent 674570e commit c2c7b75
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,9 @@ SLIDING_TOKEN_REFRESH_EXP_CLAIM
Customizing token claims
------------------------

Adding custom 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
Expand Down Expand Up @@ -309,6 +312,49 @@ 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.

Refreshing custom claims
~~~~~~~~~~~~~~~~~~~~~~~~

Certain properties of a token may be updated during the lifetime of a refresh
token. For example, if a user's name is included in the token and the user is
allowed to update their name, access tokens should be updated to reflect these
changes. If you wish to send updated custom token claims with each access
token, which are generated by the ``TokenRefreshView`` and the
``TokenRefreshSlidingView``, create a subclass of the desired view as well as a
subclass of its corresponding serializer. Here's an example of how to customize
the claims in tokens generated by the ``TokenRefreshView``:

.. code-block:: python
from django.utils.six import text_type
from rest_framework_simplejwt.serializers import TokenRefreshSerializer
from rest_framework_simplejwt.views import TokenRefreshView
from rest_framework_simplejwt.tokens import AccessToken
from my_auth_app.models import User # custom user model
class MyTokenRefreshSerializer(TokenRefreshSerializer):
def validate(self, attrs):
# get default access token
data = super().validate(attrs)
access_token_str = data.get('access')
access_token = AccessToken(access_token_str)
# get user for token
user = User.objects.get(pk=access_token['user_id'])
# update custom fields
access_token['name'] = user.name
# ...
data['access'] = text_type(access_token)
return data
class MyTokenRefreshView(TokenRefreshView):
serializer_class = MyTokenRefreshSerializer
As with the standard token views, you'll also need to include a url route to
your subclassed view.

Token types
-----------

Expand Down

0 comments on commit c2c7b75

Please sign in to comment.