gpt4 book ai didi

python - 通过第三方应用程序的 Django 自定义身份验证后端

转载 作者:行者123 更新时间:2023-12-01 05:51:45 26 4
gpt4 key购买 nike

我正在尝试在 Django 中实现一个自定义身份验证后端,它将根据来自第三方服务(Facebook、LinkedIn 等)的唯一 ID 登录用户。基本上,一旦用户对第三方服务进行 OAuth并获取唯一标识符,我想无缝登录它们。

但是我的自定义后端不起作用并返回“None”。

这是我的自定义后端:

from myapp.models import Account
from django.contrib.auth.models import User

class ThirdPartyServiceBackend(object):

def authenticate(self,acct_id=None):
if acct_id is not None:
try:
return User.objects.get(account__uniq_id=acct_id)
except:
return None

def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None

我已经在我的settings.py中启用了这个后端:

AUTHENTICATION_BACKENDS = (
'myproject.myapp.backends.ThirdPartyServiceBackend',
'django.contrib.auth.backends.ModelBackend',
)

这就是我在views.py中处理它的方式:

# oauth processing and everything goes here
try:
# login and redirect to search page

user = authenticate(acct_id=third_party_service_user_info['id'])

if user is not None:
auth_login(request,user)
return HttpResponseRedirect('/')

这在 shell 中调用工作没有问题——返回了用户。但是验证调用失败了——你对我做错了什么有什么想法吗?

最佳答案

来自 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, so if you change AUTHENTICATION_BACKENDS, you'll need to clear out session data if you need to force users to re-authenticate using different methods. A simple way to do that is simply to execute Session.objects.all().delete().

尝试一下,我遇到了同样的问题,这就是我的解决方法。

关于python - 通过第三方应用程序的 Django 自定义身份验证后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14010047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com