我将OAuth2与django-oauth-toolkit rest框架结合使用。
为了获得令牌,我通常通过以下方式对用户进行身份验证:
curl -X POST -d "grant_type=password&username=new_user&password=new_user" -u "GZwzDjPM89BceT8a6ypKGMbXnE4jWSzsyqbM3dlK:" http://localhost:8000/o/token/有办法用电子邮件而不是用户名来验证我的用户吗?
谢谢!
发布于 2017-05-26 06:27:13
是!在用户模型中将电子邮件设置为username是可能的。
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
USERNAME_FIELD = 'email'然后电子邮件现在可以作为username在请求中使用。
curl -X POST -d "grant_type=password&username=test@test.com&password=new_user" -u "GZwzDjPM89BceT8a6ypKGMbXnE4jWSzsyqbM3dlK:" http://localhost:8000/o/token/发布于 2017-05-28 10:18:00
如果您不想(或不能)创建自定义用户模型,下面是一个简单的解决方案:只需像这样覆盖rest_framework_social_oauth2.views.TokenView:
from django.contrib.auth import get_user_model
import rest_framework_social_oauth2.views
class TokenView(rest_framework_social_oauth2.views.TokenView):
def create_token_response(self, request):
email = request.POST.pop('email', None)
if email:
username = get_user_model().objects.filter(email=email[0]).values_list('username', flat=True).last()
request.POST['username'] = username
return super(TokenView, self).create_token_response(request)然后,在您的urls.conf中将这个自定义视图连接到oauth/token模式,例如:
urlpatterns = [
url(r'^oauth/token', my_auth.TokenView.as_view()), # The customized TokenView
url(r'^oauth/', include('rest_framework_social_oauth2.urls')), # Original URLs
]发布于 2017-01-25 06:47:48
我不知道为什么这个问题没有得到回答,但无论如何,我希望我的回答对遇到这个问题的人也有帮助:
丑陋但快速的方式:
将电子邮件作为用户名发送到您的POST请求中,然后找到它的真实用户名并用这些数据替换您的POST请求;所有这些都在您的中间件中:
class DisableCSRF(object):
"""Middleware for disabling CSRF in a specified app name.
"""
def process_request(self, request):
"""Preprocess the request.
"""
if (resolve(request.path_info).app_name == "api") or (
resolve(request.path_info).namespace == "oauth2_provider"):
if resolve(request.path_info).namespace == "oauth2_provider":
post_data = request.POST.copy()
true_username = User.objects.get(
email=request.POST.get("username")
).username
post_data["username"] = true_username
request.POST = post_data
setattr(request, '_dont_enforce_csrf_checks', True)
else:
pass # check CSRF token validation优雅而良好的实践方式:
创建您自己的类来请求auth令牌,这样您就可以以用户名的形式接收电子邮件。您甚至可以添加更多的自定义身份验证,如Facebook或Google登录。这绝对是最好的方法,但它需要更多的时间来开发,所以如果您有足够的时间来实现它,这取决于您。
希望现在回答这个问题还不晚。
https://stackoverflow.com/questions/35661924
复制相似问题