簡體   English   中英

通過第三方應用程序的Django自定義身份驗證后端

[英]Django custom authentication backend via third-party app

我正在嘗試在Django中實現自定義身份驗證后端,該后端將根據來自第三方服務(Facebook,LinkedIn等)的唯一ID登錄用戶。基本上,一旦用戶對第三方服務進行OAuth驗證並獲得了返回唯一標識符,我想無縫登錄。

但是我的自定義后端不起作用,並返回“無”。

這是我的自定義后端:

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('/')

這樣在外殼中調用工作就沒問題-用戶已返回。 但是驗證電話失敗了-關於我在做什么的任何想法嗎?

從Django文檔中:

用戶通過身份驗證后,Django會在用戶會話中存儲用於驗證用戶身份的后端,並在需要訪問當前身份驗證的用戶時在該會話期間重復使用相同的后端。 這實際上意味着身份驗證源將基於每個會話進行緩存,因此,如果更改AUTHENTICATION_BACKENDS,則需要強制用戶使用其他方法重新進行身份驗證,則需要清除會話數據。 一個簡單的方法就是執行Session.objects.all()。delete()。

試試看,我有同樣的問題,那是我的解決辦法。

Django可以實現第三方Auth方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM