在 django rest 框架中使用令牌身份验证返回更多信息

Posted

技术标签:

【中文标题】在 django rest 框架中使用令牌身份验证返回更多信息【英文标题】:returning more informations with token authentication in django rest framework 【发布时间】:2021-10-16 20:11:27 【问题描述】:

我已经为我的 django 项目实现了令牌认证。在 POST 请求后为用户生成令牌时。我需要用令牌返回其他信息 喜欢:

“令牌”:“令牌字符串”,

“电子邮件”:“email@email.com”,

“电话”:“12345”, “照片”:取决于照片序列化器

请问我该怎么做?这是我的代码:

模型.py

class User(AbstractUser):
    username = None
    email = models.EmailField(max_length=100, 
               verbose_name='email', unique=True)
    phone = models.CharField(max_length=100)

    
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = UserManager()

Views.py

class AuthToken(auth_views.ObtainAuthToken):
    serializer_class = AuthTokenSerializer
    if coreapi is not None and coreschema is not 
                         None:
        schema = ManualSchema(
            fields=[
                coreapi.Field(
                    name="email",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Email",
                        description="Valid email 
                           for authentication",
                    ),
                ),
                coreapi.Field(
                    name="password",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Password",
                        description="Valid password for authentication",
                    ),
                ),
            ],
            encoding="application/json",
        )

序列化器.py

class AuthTokenSerializer(serializers.Serializer):

    email = serializers.EmailField(label=_("Email"))
    password = serializers.CharField(
        label=_("Password",),
        style='input_type': 'password',
        trim_whitespace=False
    )

    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')

        if email and password:
            user = 
 authenticate(request=self.context.get('request'),
                                email=email, password=password)

       if not user:
            msg = ('Unable to log in with 
                   provided credentials.')
            raise 
                serializers.ValidationError(msg, 
                  code='authorization')
        else:
            msg = ('Must include "username" and 
                  "password".')
            raise serializers.ValidationError(msg, 
              code='authorization')
        attrs['user'] = user
        return attrs

class UserSerializer(serializers.ModelSerializer):
    photo = PhotoSerializer()
    class Meta:
        model = User
        fields = ['id', 'email','phone', 'photo', ']

【问题讨论】:

【参考方案1】:

只需覆盖 auth_views.ObtainAuthToken 类的 post 函数并将您的数据添加到响应中:

class AuthToken(auth_views.ObtainAuthToken):
    serializer_class = AuthTokenSerializer
    if coreapi is not None and coreschema is not 
                         None:
        schema = ManualSchema(
            fields=[
                coreapi.Field(
                    name="email",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Email",
                        description="Valid email 
                           for authentication",
                    ),
                ),
                coreapi.Field(
                    name="password",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Password",
                        description="Valid password for authentication",
                    ),
                ),
            ],
            encoding="application/json",
        )

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response(
            'token': token.key,
            'email': user.email,
            # and your extra data required
        )

【讨论】:

它工作了谢谢,但是如何返回像 UserSerializer 这样的用户信息?所有字段,甚至是嵌套在 UserSerializer 中的字段 @Zero0 我认为如果你只是导入 UserSerailizer 并使用它应该可以完成工作......我在这里没有看到任何问题,如果有请解释更多...... 在 UserSerializer 中。我有嵌套的序列化程序。我也想返回这些字段。例如用户发布的公告。 class UserSerializer(serializers.ModelSerializer): photo = PhotoSerializer() 公告 = AnnouncementSerializer(many=True, read_only=True) rating = SerializerMethodField('rating_avg') number_of_ratings = SerializerMethodField('rating_number') Emma,我没有好的解决方案,也许你可以在不同的序列化器中序列化它们,然后将它们放入一个字典对象中,然后作为响应返回?

以上是关于在 django rest 框架中使用令牌身份验证返回更多信息的主要内容,如果未能解决你的问题,请参考以下文章

如何在 django rest 框架中验证 jwt 身份验证中的令牌

使用 Django Rest 框架进行 JWT 令牌身份验证

如何使用迁移框架添加 Django REST 框架身份验证令牌

使用 otp 获取 api 令牌的 Django REST 框架的 JWT 身份验证

令牌身份验证在 Django Rest 框架上不起作用

令牌身份验证在 django rest 框架上的生产中不起作用