我在网上发现,我们可以通过在我们的网址url(r'^login/', ObtainJSONWebToken.as_view(serializer_class=CustomJWTSerializer)),
中查看JSONWebTokenSerializer来覆盖JSONWebTokenSerializer
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)
并且肯定存在它虽然有效
您可以使用其他设置 - 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, }