Jeffrey Ma
Jeffrey Ma

Reputation: 11

Can't get Flask-Session to send session cookie (Python+React)

So basically the issue is that my flask server is not saving the sessions I create in one route to access in a separate route. The sessions in my /login works, it returns the refresh and access token, however, the same cannot be said about the /auth path. I believe that there is something wrong with my CORS which is blocking my session cookies, but I'm not necessarily sure.

This is my flask app.py code:

from flask import Flask, jsonify, request, url_for,session
from flask_cors import CORS, cross_origin
from google_auth_oauthlib.flow import Flow
from google.oauth2 import id_token
from flask_session import Session
import os,pathlib,requests


app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
CORS(app,supports_credentials=True)
Session(app)

GOOGLE_CLIENT_ID = "----------------------------"
client_secrets_file = os.path.join(pathlib.Path(__file__).parent, "client_secret.json")
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'



@app.route('/login', methods=['POST'])
@cross_origin()
def login():
    flow = Flow.from_client_secrets_file(
        'client_secret.json',
        scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'],
        redirect_uri='http://localhost:3000',
        )
    flow.fetch_token(code=request.get_json()['code'])
    credentials = flow.credentials
    session['access_token'] = credentials.token
    session['refresh_token'] = credentials.refresh_token
    session.permanent = True
    return jsonify({"access_token":session.get('access_token'),"refresh_token":session.get('refresh_token')})

@app.route('/auth', methods=['POST'])
@cross_origin()
def authenticate():
    #This is just temp code to test if sessions work
    return jsonify(session['access_token'])

@app.route('/refresh', methods=['POST'])
@cross_origin()
def refresh():
    # check if refresh token is in session if not prompt user to login
    # if user refresh token exists, contact google api to create new access token
    # return either "403" relogin or "200" {new access token}
    pass

if __name__ == '__main__':
    app.run(debug=True)

This is my react code:

import axios from "axios";
import { useContext, useEffect, useState } from "react"
import { GlobalContext } from "../globalState/globalState";
import ErrorPage from "./errorPage";

const Authenticate = ({element}) => {
    const [message, setMessage] = useState();
    const {accessToken} = useContext(GlobalContext);

    const checkValidToken = async() => {
        //console.log(accessToken)
        return await axios.post(
            "http://localhost:5000/auth",{headers: {
                'Content-Type': 'application/json'
              },
              withCredentials: true
            }
        ).then((resp)=> {
            console.log(resp)
        })
    }

    useEffect(()=> {
        // check if refresh token is a thing, if not post request localhost:5000/refresh
        checkValidToken().then((resp)=> {
            if(resp)
                setMessage(element);
            else
                setMessage(<ErrorPage />)
        })
    },[])

    return (<>{message}</>);

}

export default Authenticate;

This is the error I get when I make a /auth request.

Traceback (most recent call last):
  File "C:\Program Files\Python39\Lib\site-packages\flask\app.py", line 2091, in call
    return self.wsgi_app(environ, start_response)
  File "C:\Program Files\Python39\Lib\site-packages\flask\app.py", line 2076, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Program Files\Python39\Lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function
    return cors_after_request(app.make_response(f(args, **kwargs)))
  File "C:\Program Files\Python39\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Program Files\Python39\Lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Program Files\Python39\Lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function
    return cors_after_request(app.make_response(f(args, kwargs)))
  File "C:\Program Files\Python39\Lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Program Files\Python39\Lib\site-packages\flask\app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(req.view_args)
  File "C:\Program Files\Python39\Lib\site-packages\flask_cors\decorator.py", line 128, in wrapped_function
    resp = make_response(f(*args, **kwargs))
  File "C:\Users-------------------\Documents\GitHub\RememberMyProject\app\pythonxr\app.py", line 41, in authenticate
    return jsonify(session['access_token'])
KeyError: 'access_token'

Upvotes: 0

Views: 1680

Answers (1)

thespiderdev
thespiderdev

Reputation: 76

Try initializing your CORS with CORS(app, supports_credentials=True).

Check here.

Upvotes: 0

Related Questions