Django OAuth2:使用电子邮件而不是用户名进行身份验证
我将OAuth2与django oauth工具包django rest框架一起使用 为了获得令牌,我通常通过以下方式对用户进行身份验证:Django OAuth2:使用电子邮件而不是用户名进行身份验证,django,oauth-2.0,django-rest-framework,Django,Oauth 2.0,Django Rest Framework,我将OAuth2与django oauth工具包django rest框架一起使用 为了获得令牌,我通常通过以下方式对用户进行身份验证: curl -X POST -d "grant_type=password&username=new_user&password=new_user" -u "GZwzDjPM89BceT8a6ypKGMbXnE4jWSzsyqbM3dlK:" http://localhost:8000/o/token/ 有没有办法用电子邮件而不是用户名来验证我
curl -X POST -d "grant_type=password&username=new_user&password=new_user" -u "GZwzDjPM89BceT8a6ypKGMbXnE4jWSzsyqbM3dlK:" http://localhost:8000/o/token/
有没有办法用电子邮件而不是用户名来验证我的用户
谢谢 我不知道为什么这个问题一直没有得到回答,但无论如何,我希望我的回答对遇到这个问题的人也有用: 丑陋但快速的方法: 在您的发帖请求中以用户名发送电子邮件,然后找到其真实用户名,并用此数据替换您的发帖请求;所有这些都在您的中间件中:
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
优雅而良好的练习方式:
创建您自己的类以请求身份验证令牌,以便您可以将电子邮件作为用户名接收。您甚至可以添加更多自定义身份验证,如Facebook或Google登录。这绝对是最好的方法,但是它需要更多的时间来开发,所以如果您有足够的时间来实现它,这取决于您
希望现在回答这个问题还不算太晚。是的!可以通过在用户模型中将电子邮件设置为
用户名
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'
然后,电子邮件现在可以在请求中用作用户名
curl -X POST -d "grant_type=password&username=test@test.com&password=new_user" -u "GZwzDjPM89BceT8a6ypKGMbXnE4jWSzsyqbM3dlK:" http://localhost:8000/o/token/
如果您不想(或不能)创建自定义用户模型,这里有一个简单的解决方案:只需覆盖rest\u framework\u social\u 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
]
在django 1.11中新增。对我来说有点晚了,但很高兴知道,谢谢!url应该是
oauth/token/
,以覆盖oauth2的默认url