Search code examples
django-rest-frameworkdjango-rest-framework-simplejwt

Use Django AUTH_USER model to pass data with JWT Token (Eg.first_name, last_name)


I'm working on Django RF using ModelViewSet where I'll be using JWT Token Authentication. I want to use default django auth_user model rather than creating new custom user model.

#serializer.py
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    class Meta:
    model = User
    fields = ('username','first_name')
    def validate(self, attrs):
        data = super().validate(attrs)
        refresh = self.get_token(self.user)
        data['refresh'] = str(refresh)
        data.pop('refresh', None) # remove refresh from the payload
        data['access'] = str(refresh.access_token)

        # Add extra responses here
        data['username'] = self.user.username
        data['first_name'] = self.user.first_name
        data['last_name'] = self.user.last_name
        return data

views.py
class TokenObtainPairView(TokenObtainPairView):
# Replace the serializer with your custom
serializer_class = MyTokenObtainPairSerializer
# token_obtain_pair = TokenObtainPairView.as_view()



class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
class Meta:
    model = User
    fields = ('username','first_name')
@classmethod
def get_token(cls, user):
    token = super().get_token(user)
    token['username'] = user.username
    token['first_name'] = user.first_name
    return token

Solution

  • If you don´t set AUTH_USER_MODEL = 'myapp.MyUser' in settings.py, you will use User by default instead of MyUser.

    settings.py

    And if you use simplejwt you have to assign the authentication class.

    REST_FRAMEWORK = {
        ...
        'DEFAULT_AUTHENTICATION_CLASSES': (
            ...
            'rest_framework_simplejwt.authentication.JWTAuthentication',
        )
        ...
    }
    

    CustomTokenObtainPairView without customizing token

    Okay got it. Thanks alot @Klim Bim. Can you do me a favour. Can you tell me how can i add other fields with simple-jwt token. I have tried using Custom TokenObtaibPairView' but all i'm getting is user_id.

    Either you can customize token claims or you can add data to response.

    serializer.py

    class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
        @classmethod
        def get_token(cls, user):
            token = super().get_token(user)
            token['username'] = user.username
            token['first_name'] = user.first_name
    
            return token
    

    views.py

    class CustomTokenObtainPairView(TokenObtainPairView):
    
       serializer_class = CustomTokenObtainPairSerializer
    
       def post(self, request, *args, **kwargs):
    
          response = super().post(request, *args, **kwargs)
          response.data['custom_key'] =  'my_custom_data'
          
          return response
    

    urls.py

    urlpatterns = [
        path('token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'),
    ]
    

    postman

    enter image description here