在django中,登录后如何检测哪个auth后端对用户进行了身份验证? [英] In django, after a login how can I detect which auth backend authenticated the user?
问题描述
我试图在我的视图中区分几个Django身份验证后端(它们是外部软件包,我最好不希望对其进行修改). django.contrib.auth
docs表示将按顺序尝试auth后端(settings.AUTHENTICATION_BACKENDS
),第一个进行身份验证的后端将返回并设置request.user
,如果有异常,则拒绝身份验证.但这并没有说明我如何根据哪个后端对用户进行身份验证来区分请求.
I'm trying to distinguish between a couple of Django authentication backends (which are external packages and I preferably don't want to modify them) in my views. django.contrib.auth
docs says auth backends (settings.AUTHENTICATION_BACKENDS
) will be tried in order and the first that does authenticate, will return and set request.user
and if any raises an exception, authentication is refused. But it does not say how can I distinguish between requests depending on which backend has authenticated the user.
这可能吗?以及如何?
推荐答案
如
用户通过身份验证后,Django会在用户会话中存储用于后端用户身份验证的后端,并在需要访问当前身份验证用户的会话期间重复使用相同的后端.这实际上意味着身份验证源将按会话进行缓存
Once a user has authenticated, Django stores which backend was used to authenticate the user in the user’s session, and re-uses the same backend for the duration of that session whenever access to the currently authenticated user is needed. This effectively means that authentication sources are cached on a per-session basis 实际上,使用功能 Actually, this information is stored when function 因此,您应该检查当前请求的会话以获取密钥 So, you should check current request's session for key 这篇关于在django中,登录后如何检测哪个auth后端对用户进行了身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
login(request, user, backend=None)
时会存储此信息(请参见login(request, user, backend=None)
is used (see django.contrib.auth.__init__.py
). After user has been authenticated, following session information are stored:SESSION_KEY = '_auth_user_id'
BACKEND_SESSION_KEY = '_auth_user_backend'
HASH_SESSION_KEY = '_auth_user_hash'
# [...]
request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
request.session[BACKEND_SESSION_KEY] = backend
request.session[HASH_SESSION_KEY] = session_auth_hash
BACKEND_SESSION_KEY
,以找到用于验证用户身份的后端.BACKEND_SESSION_KEY
to find the backend used to authenticate user.