Django 在重定向到其他视图之间不保存会话

问题描述 投票:0回答:4

我正在使用 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')

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

python django session oauth
4个回答
1
投票

保存会话后使用此功能

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


1
投票

我的问题是谷歌身份验证将其重定向到 localhost:8000,但会话是为 127.0.0.1:8000 创建的。 我从 localhost:8000/callback/ 更改了重定向 Uri。到 127.0.0.18000/callback/ 并解决了问题。


0
投票

过去两天我一直在努力解决这个问题的各个方面。对我来说,这是一个 CloudFront 配置问题,因为我通过 Elastic Beanstalk 和 CloudFront 部署了 Django 应用程序。您需要确保您的 CloudFront 发行版不会阻止 cookie 和查询字符串。


0
投票

我在 settings.py 中有选项 SESSION_COOKIE_SECURE = True 。将其注释掉,会话变量将被保存

© www.soinside.com 2019 - 2024. All rights reserved.