Search code examples
djangodjango-rest-frameworkjwtdjango-rest-framework-jwt

Getting user id returned with JWT


Good morning,

I am writing my first DRF API and am using django-rest-framework-jwt (https://getblimp.github.io/django-rest-framework-jwt/) to handle JWT auth.

I am using the built in views currently:

from rest_framework_jwt.views import obtain_jwt_token
from rest_framework_jwt.views import refresh_jwt_token

 urlpatterns = [
    path('auth/obtain_token/', obtain_jwt_token),
    path('auth/refresh_token/', refresh_jwt_token),

but need to return some user information back to the UI (VueJS). I would like to store the user ID and name information into the Vuex store to pass into subsequent API calls and to present to the user ("Hello Jim!").

I found this which discussing adding a custom function for jwt payload response: jwt rest framework returning user id with token

I am not sure WHERE to do this though...

Thanks for your help in clarifying.

BCBB


Solution

  • There are a couple of solutions

    1) First of all the user id is encoded in the JWT, you can decode that in your js yourself.

    2) You can override the payload returned from django-rest-framework-jwt as follows: put the following code for example in your accounts app inside a file called utils.py

    def jwt_response_payload_handler(token, user=None, request=None):
        return {
            'token': token,
            'username': user.username,
            'user_id' : user.id,
            'email' : user.email
        }
    

    and in rest-framework-jwt settings replace

        'JWT_RESPONSE_PAYLOAD_HANDLER':
        'rest_framework_jwt.utils.jwt_response_payload_handler',
    

    With this

        'JWT_RESPONSE_PAYLOAD_HANDLER':
        'accounts.utils.jwt_response_payload_handler',