Djangorestframework-simplejwt: Adding token claims when creating tokens manually

Created on 10 Aug 2019  路  4Comments  路  Source: jazzband/djangorestframework-simplejwt

I currently have an APIView that authenticates first to another server using request data and obtains a value (unfortunately this is the only way). I have updated the example to include this value in the get_tokens_for_user method:

def get_tokens_for_user(self, data):
    refresh = RefreshToken.for_user(data['user'])
    refresh['value'] = data['value']

    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }

This returns a token with the claim however when verifying on a platform such as https://www.jsonwebtoken.io/ or https://jwt.io/ it says that the signing key has failed. How do I go about implementing this so that jwt token is proper?

Most helpful comment

For anyone else finding this: I achieved by using a custom serializer as described in the docs. I have my serializer like this:

class AuthTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        token['name'] = user.first_name
        # Add other claims here as required
        return token

And then in my view where I manually create a new token:

user = User.objects.get(username='example')
# Optionally perform some operations against the user.
refresh = AuthTokenObtainPairSerializer.get_token(user)

return Response(data={'refresh': str(refresh), 'access': str(refresh.access_token)})

In my case, this successfully returns a fresh token with new claims.

All 4 comments

+1, I would also like to do this

+1, I'm also in need of doing this in a reliable way.

I have implemented the standard token obtain as outlined in the documentation which works fine for the two standard routes.

However the implementation I'm using is also passing through an OTP token collection/verification so the JWT tokens need to be verified after the OTP has been checked (rather than a username/password JWT token obtain request - the OTP is linked to a user so I already know the user at the point of which I need to generate JWT tokens)

The documentation linked to above for custom claim data works, and so does the code you have specified above for my manual generation.

I also find that the verifiers you have linked to show initially that they are invalid, however the first link if I press 'tab' after pasting my JWT token into the box, the Payload box updates with an iat key and then it goes green.

Interestingly, not even stock functionality for the JWT tokens (with all my custom classes removed) can get the second link to verify green so not sure if this is a red herring, or the validator is broken? (Going on the assumption here that the simplejwt library isn't spitting out invalid tokens by defaultl!?)

For anyone else finding this: I achieved by using a custom serializer as described in the docs. I have my serializer like this:

class AuthTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        token['name'] = user.first_name
        # Add other claims here as required
        return token

And then in my view where I manually create a new token:

user = User.objects.get(username='example')
# Optionally perform some operations against the user.
refresh = AuthTokenObtainPairSerializer.get_token(user)

return Response(data={'refresh': str(refresh), 'access': str(refresh.access_token)})

In my case, this successfully returns a fresh token with new claims.

@jayps +1, a good solution!

Was this page helpful?
0 / 5 - 0 ratings