使用 Django AUTH_USER 模型通过 JWT Token 传递数据 (Eg.first_name, last_name)

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

我正在使用 ModelViewSet 处理 Django RF,我将在其中使用 JWT 令牌身份验证。我想使用默认的 django auth_user 模型而不是创建新的自定义用户模型。

#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

如果您不在 settings.py 中设置 AUTH_USER_MODEL = 'myapp.MyUser',您将默认使用 User 而不是 MyUser

settings.py

如果您使用 simplejwt,则必须分配身份验证 class。

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

没有自定义token的CustomTokenObtainPairView

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.

您可以自定义 token claims 或向响应中添加数据。

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'),
]

邮递员[=3​​0=]