gpt4 book ai didi

python - Django 不在重定向到其他 View 之间保存 session

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

我正在使用 django session 数据来验证 oauth_2 身份验证是否成功。但是,django 不会在 View 之间保存 session 数据。

@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')

在第一行授权下看我打印状态旁边的注释。你为什么认为这是? session 数据不应该在 View 之间共享。

最佳答案

保存 session 后使用它 request.session.modified = True

request.session['oauth_state'] = state
request.session.modified = True

https://docs.djangoproject.com/en/1.11/topics/http/sessions/#when-sessions-are-saved

关于python - Django 不在重定向到其他 View 之间保存 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45340592/

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