【发布时间】:2023-03-06 13:52:01
【问题描述】:
我正在使用 django 会话数据来验证 oauth_2 身份验证是否成功。但是,django 不会在视图之间保存会话数据。
@never_cache
def login(request):
microsoft = OAuth2Session(client_id,scope=scope,redirect_uri=redirect_uri)
global state
authorization_url, state = microsoft.authorization_url(authorization_base_url)
# State is used to prevent CSRF, keep this for later.
request.session['oauth_state'] = state
return HttpResponseRedirect(authorization_url)
@never_cache
def authorization(request):
print(request.session.get('oauth_state')) ##This is where I'm having a problem. 'oauth_state' prints none!
microsoft = OAuth2Session(client_id,scope=scope,redirect_uri=redirect_uri)
token = ""
try:
users = 'https://graph.microsoft.com/v1.0/me' ##msgraph query url-
##This query is purelyjust used to
##authenticate user!
token = microsoft.fetch_token(token_url, client_secret=client_secret,code=request.GET.get('code', ''))
header = {'Authorization': 'Bearer ' + token['access_token']}
response = requests.get(url = users, headers = header)
print(response.text)
print(response.status_code)
if int(response.status_code) != 200: ##if status code is not 200, then authentication failed. Redirect to login.
print ('Not validated. Return to login.')
return redirect('http://localhost:8000/login')
check_for_authorized = True
print(token)
except Exception as e:
print ('User not does not have authentication rights')
return redirect('http://localhost:8000/login')
return HttpResponseRedirect('http://localhost:8000/search')
看第一行授权下我的打印状态旁边的注释。你为什么认为这是?会话数据不应该在视图之间共享。
【问题讨论】:
-
是的,它应该是共享的(通常是)。你能解释一下
state的全局用法吗?如果您实际上不需要它来做任何事情,请尝试删除它。 -
您必须绝对不要为
state变量使用全局变量。 -
我在使用谷歌身份验证时遇到了完全相同的问题,当我尝试访问回调函数中的状态时,它没有返回。你解决了吗?
-
你使用的是什么版本的 Django?
标签: python django session oauth