我可以设置单独的OAuth提供程序服务器(PS)和资源服务器(RS)。我可以使用username/password
并从PS正常获取bearer
令牌。但我想通过接受用户的email/password
问题:
如何在基于REST的OAuth中使用username/email + password
身份验证?
尝试:
https://github.com/jazzband/django-oauth-toolkit/blob/master/oauth2_provider/oauth2_validators.py
我正在第590行尝试validate_user
。
HackAround:
经过8个小时的阅读。我建议以此为由。它有效,但不专业。我更喜欢best practice
的方式来解决这个问题。
欢迎任何评论和答案。
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.validators import EmailValidator
def validate_user(self, username, password, client, request, *args, **kwargs):
"""
Check username and password correspond to a valid and active User
"""
# check the given `username` variable is an email or not?
# If it is an email. Then query by email argument
# else do a normal search
email_validator = EmailValidator()
try:
email_validator(username)
except ValidationError:
u = authenticate(username=username, password=password)
if u is not None and u.is_active:
request.user = u
return True
return False
else:
# `username` is a valid email
# Immitate Model.Backend.authenticate()
try:
user = UserModel.objects.get(email=username)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
UserModel().set_password(password)
else:
# Imitate `ModelBackend.user_can_authenticate`
is_active = getattr(user, 'is_active', None)
user_can_authenticate = is_active or is_active is None
if user.check_password(password) and user_can_authenticate:
if user is not None and user.is_active:
request.user = user
return True
return False