Django自定义身份验证 -

我正在尝试使用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)

2 years ago

Django使用以下(从 django.contrib.auth.__init__ )获取登录用户并将其传递给 AuthenticationMiddleware 以设置 request.user

SESSION_KEY = '_auth_user_id'
BACKEND_SESSION_KEY = '_auth_user_backend'

def get_user(request):
    from django.contrib.auth.models import AnonymousUser
    try:
        user_id = request.session[SESSION_KEY]
        backend_path = request.session[BACKEND_SESSION_KEY]
        backend = load_backend(backend_path)
        user = backend.get_user(user_id) or AnonymousUser()
    except KeyError:
        user = AnonymousUser()
    return user

可能是您将错误的值传递给 backend.get_user ,因此无法检索到正确的用户,因此请将 AnonymousUser 设置为请求 . 您可以尝试调试以查看 backend.get_user 是否按预期工作

2 years ago

问题很老,也许你找到了答案,但是用户没有登录后续请求的原因是 authenticate 方法没有将经过身份验证的用户保存在会话中,因为您需要使用 login 方法进行身份验证后相同的模块 .

来自docs:

def authenticate(request=None, **credentials):
    """
    If the given credentials are valid, return a User object.
    """

def login(request, user, backend=None):
    """
    Persist a user id and a backend in the request. This way a user doesn't
    have to reauthenticate on every request. Note that data set during
    the anonymous session is retained when the user logs in.
    """

[资源]

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