首页 > 解决方案 > 在 django rest 框架中使用令牌身份验证返回更多信息

问题描述

我已经为我的 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()

视图.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', ']

标签: pythondjangodjango-modelsdjango-rest-frameworktoken

解决方案


只需覆盖 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
        })

推荐阅读