为什么重写重置的JSONWebTokenSerializer只保留返回令牌?蟒蛇

时间:2017-01-26 18:30:56

标签: python validation django-rest-framework token serializer

我在网上发现,我们可以通过在我们的网址中覆盖JSONWebTokenSerializer来覆盖它 url(r'^login/', ObtainJSONWebToken.as_view(serializer_class=CustomJWTSerializer)), 并且在视野中我有

class CustomJWTSerializer(JSONWebTokenSerializer):

    def __init__(self, *args, **kwargs):
        super(JSONWebTokenSerializer, self).__init__(*args, **kwargs)

        self.fields['email'] = serializers.CharField()
        self.fields['password'] = PasswordField(write_only=True)

    def validate(self, attrs):
        credentials = {
            'username': attrs.get('email'),
            'password': attrs.get('password')
        }

        print(credentials)

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise serializers.ValidationError(msg)

                payload = jwt_payload_handler(user)

                return {
                    'token': jwt_encode_handler(payload),
                    'user': user
                }
            else:
                msg = _('Unable to login with provided credentials.')
                raise serializers.ValidationError(msg)
        else:
            msg = _('Must include "{username_field}" and "password".')
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)

有了这个,我可以开始覆盖原文,但不知何故,返回对象总是只是令牌。

不知怎的,我无法找到它的生成位置,因为

,它看起来确实如此
            return {
                'token': jwt_encode_handler(payload),
                'user': user
            }

即使这样,用户也不会仅返回令牌。 我甚至尝试取出整个回报并获得return{}但是使用正确的凭证,它仍会返回{"token": null}

之类的内容

我甚至尝试使用return Response({}),但仍然从{"token": null}获取user object,为什么不显示我的print (user)作为回复?我使用{{1}}并确定存在它虽然

有效

1 个答案:

答案 0 :(得分:6)

您可以使用其他设置 - JWT_RESPONSE_PAYLOAD_HANDLER - 在json响应中返回密钥和用户。参见文档http://getblimp.github.io/django-rest-framework-jwt/,有一个使用JWT_RESPONSE_PAYLOAD_HANDLER的例子。

这是我的代码示例:

settings.py

JWT_AUTH = {
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'back.views.jwt_response_payload_handler',
}

在back / view.py

from rest_framework import serializers
from django.contrib.auth.models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username')


def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user': UserSerializer(user, context={'request': request}).data,
    }