Django not saving session between redirects to other views

Viewed 2900

I am using django session data in order to verify that oauth_2 authentication has succeeded. However, django is not saving session data between views.

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

Look at the comment beside my print state under the first line of authorization. Why do you think this is? Shouldn't session data be shared between views.

3 Answers

The issue in my case was that google authentication was redirecting it to localhost:8000 but the session was created for 127.0.0.1:8000. I changed my redirect Uri from localhost:8000/callback/. to 127.0.0.18000/callback/ and It solved the issue.

I've been struggling with various aspects of this for the last two days. For me it turned out to be a CloudFront config issue since I deployed my Django app via Elastic Beanstalk and CloudFront. You need to ensure that your CloudFront distribution is not blocking cookies and query strings.

Related