您需要向身份验证功能添加请求。请参阅下面的示例代码。
序列化程序.py
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
def _authenticate_user_email(self, email, password, request):
# This is key: Pass request to the authenticate function
self.user = authenticate(email=email, password=password, request=request)
return self.user
def validate(self, attrs):
password = attrs.get('password')
email = attrs.get('email')
request = self.context.get('request') # <<=== Grab request
self.user = self._authenticate_user_email(email, password, request)
# All error handling should be done by this code line
refresh = self.get_token(self.user)
data = {}
data['refresh'] = str(refresh)
data['access'] = str(refresh.access_token)
return data
视图.py
from rest_framework_simplejwt.views import TokenObtainPairView
from authy.serializers import MyTokenObtainPairSerializer
class MyTokenObtainPairView(TokenObtainPairView):
serializer_class = MyTokenObtainPairSerializer
网址.py
from authy.views import MyTokenObtainPairView
url(r'^/auth/api/token/$', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
还值得一提的是,简单的 jwt lib 使用了身份验证功能,但是它不传递请求参数。因此,您需要自己调用身份验证、get_token 并返回数据对象。
另外,如果你扩展了 django 的 AbstractBaseUser 模型。并设置USERNAME_FIELD。然后使用参数用户名而不是电子邮件。例如:验证(用户名=电子邮件,密码=密码,请求=请求)