3
我試圖尋找this answer,以及使用Django會議here。自定義驗證後端中間件
用我的自定義身份驗證登錄工作正常,但我想驗證與中間件的每個請求上的令牌,我不知道如何存儲令牌,以便它可以從中間件訪問以及作爲意見。
我想從我的身份驗證後端存儲會話變量,但試圖從我的觀點訪問它時,我總是會得到一個關鍵的錯誤。
有沒有很好的方法來做到這一點?
謝謝!
class MyAuthBackend(object):
supports_inactive_user = False
supports_object_permissions = False
supports_anonymous_user = False
def authenticate(self, username=None, password=None):
# This makes a call to my API to varify login, then return token if valid. I need to make login_valid accessible to my middleware and views.
login_valid = auth.login(username,password)
if login_valid:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
user = User(username=username, password='never_used')
user.is_active = True
user.save()
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
class MyAuthMiddleware(object):
def process_request(self, request):
if not request.user.is_anonymous():
# API call to my backend to check if token is still valid. If not, return to login page.
token_variable = ???????????
if isTokenStillValid(token_variable):
return
else:
return HttpResponseRedirect('/accounts/login/?next=%s' % request.path)