我在网上发现,我们可以通过在url中使用这个来覆盖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作为响应呢?我使用了cc,并且确信它是有效的。

最佳答案

您可以使用附加设置-jwt_response_payload_handler-在json响应中返回密钥和用户。参见文档http://getblimp.github.io/django-rest-framework-jwt/,这里有一个使用jwt_response_payload_处理程序的示例。
这是我的代码示例:
设置.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,
    }

10-04 21:44
查看更多