使用用户名或电子邮件登录Django Rest JWT? [英] Django Rest JWT login using username or email?
问题描述
我正在使用 django-rest-jwt 在我的应用中进行身份验证.
I am using django-rest-jwt for authentication in my app.
默认情况下,用户名"字段用于使用户生效,但我希望让用户使用电子邮件或用户名登录.
By default it user username field to autenticate a user but I want let the users login using email or username.
django-rest-jwt是否支持任何手段来完成此任务. 我知道最后一个选择是编写自己的登录方法.
Is there any mean supported by django-rest-jwt to accomplish this. I know the last option would be write my own login method.
推荐答案
无需编写自定义身份验证后端或自定义登录方法.
No need to write a custom authentication backend or custom login method.
自定义序列化程序继承JSONWebTokenSerializer,重命名"username_field"并覆盖def validate()方法.
A Custom Serializer inheriting JSONWebTokenSerializer, renaming the 'username_field' and overriding def validate() method.
这非常适合"username_or_email"和"password"字段,用户可以在其中输入用户名或电子邮件并获取JSONWebToken以获取正确的凭据.
This works perfectly for 'username_or_email' and 'password' fields where the user can enter its username or email and get the JSONWebToken for correct credentials.
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import ugettext as _
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
User = get_user_model()
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
jwt_get_username_from_payload = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER
class CustomJWTSerializer(JSONWebTokenSerializer):
username_field = 'username_or_email'
def validate(self, attrs):
password = attrs.get("password")
user_obj = User.objects.filter(email=attrs.get("username_or_email")).first() or User.objects.filter(username=attrs.get("username_or_email")).first()
if user_obj is not None:
credentials = {
'username':user_obj.username,
'password': password
}
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 log in 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)
else:
msg = _('Account with this email/username does not exists')
raise serializers.ValidationError(msg)
在urls.py中:
url(r'{Your url name}$', ObtainJSONWebToken.as_view(serializer_class=CustomJWTSerializer)),
这篇关于使用用户名或电子邮件登录Django Rest JWT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!