我刚刚经历了同样的理解之旅,因为我希望返回用户,并且还允许电子邮件或用户名登录。文档并不完全清楚,但如auth令牌所述,您可以对JWT执行相同的操作。 obtain_auth_token是ObtainAuthToken,因为obtain_jwt_token是ObtainJSONWebToken。 这是我的覆盖登录方法:
from django.contrib.auth.models import User
from api.serializers import UserSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.views import ObtainJSONWebToken
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
class LoginView(ObtainJSONWebToken):
def post(self, request, *args, **kwargs):
# by default attempts username/passsword combination
response = super(LoginView, self).post(request, *args, **kwargs)
# token = response.data['token'] # don't use this to prevent errors
# below will return null, but not an error, if not found :)
res = response.data
token = res.get('token')
# token ok, get user
if token:
user = jwt_decode_handler(token) # aleady json - don't serialize
else: # if none, try auth by email
req = request.data # try and find email in request
email = req.get('email')
password = req.get('password')
username = req.get('username')
if email is None or password is None:
return Response({'success': False,
'message': 'Missing or incorrect credentials',
'data': req},
status=status.HTTP_400_BAD_REQUEST)
# email exists in request, try to find user
try:
user = User.objects.get(email=email)
except:
return Response({'success': False,
'message': 'User not found',
'data': req},
status=status.HTTP_404_NOT_FOUND)
if not user.check_password(password):
return Response({'success': False,
'message': 'Incorrect password',
'data': req},
status=status.HTTP_403_FORBIDDEN)
# make token from user found by email
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
user = UserSerializer(user).data
return Response({'success': True,
'message': 'Successfully logged in',
'token': token,
'user': user},
status=status.HTTP_200_OK)
您可以更改默认仅通过电子邮件,如果你请通过自定义Django的权威性模型来检查,但我很高兴有这两个选项。
我开始创建api样板。有一个requirements.txt文件和一个config.example.py文件供任何想要拉下来查看其余内容的人使用。 https://github.com/garyburgmann/django-api-boilerplate
我不明白你想要做什么。也许如果你有一个更好的例子你的目标和实际的代码。对于智威汤逊,我使用http://getblimp.github.io/django-rest-framework-jwt/,它工作正常,并且非常容易定制jwt响应。 –
如果我是正确的,你正试图自定义返回一个基于一些标准的令牌。随机猜测。 –