我正在尝试使用django进行自定义身份验证,我编写了一个类并使用authenticate和get_user方法填充它,我还将此身份验证添加到settings.py文件中的AUTHENTICATION_BACKENDS .
我已经调用了authenticate方法,并在我的视图中进行了登录 .
一切似乎都很好,
登录后
-
is_authenticated为用户返回true,
-
user.backends设置为我的自定义后端 .
-
sessionid cookie已在我的浏览器中设置
但随后的请求有request.user匿名,无法弄清楚原因,需要你的帮助 . 分享下面的代码,我只是尝试它来学习自定义身份验证 .
views.py
def home(request):
if not request.user.is_authenticated():
user=authenticate(username=None,passwd=None,request=request)
if not user:
return HttpResponse("Login Failed")
else:
login(request,user)
return HttpResponse("Logged in Successfully")
cusauth.py
class CustomloginBackend:
def authenticate(self,username=None,passwd=None,request=None):
return self.get_user("praveen.madhavan")
def get_user(self,username):
try:
return User.objects.get(username=username)
except Exception as e:
return False
可能是什么问题呢 ?
谢谢
Praveen.M
2 回答
Django使用以下(从
django.contrib.auth.__init__
)获取登录用户并将其传递给AuthenticationMiddleware
以设置request.user
可能是您将错误的值传递给
backend.get_user
,因此无法检索到正确的用户,因此请将AnonymousUser
设置为请求 . 您可以尝试调试以查看backend.get_user
是否按预期工作问题很老,也许你找到了答案,但是用户没有登录后续请求的原因是
authenticate
方法没有将经过身份验证的用户保存在会话中,因为您需要使用login
方法进行身份验证后相同的模块 .来自docs:
[资源]
https://docs.djangoproject.com/en/2.1/_modules/django/contrib/auth/#authenticate
[文档]
https://docs.djangoproject.com/en/2.1/topics/auth/default/#django.contrib.auth.authenticate
https://docs.djangoproject.com/en/2.1/topics/auth/default/#django.contrib.auth.login