Why does my Flask React.js session not work?

Issue

I’m making the login for a app in react with the backend in flask but the session is not working.

The flask app is running in a remote server on pythonanywhere and I’m testing the react app on my localhost:3000

Here’s the code for the flask app:

    app = Flask(__name__)
    
    app.config["SESSION_PERMANENT"] = True
    app.config["SESSION_TYPE"] = "filesystem"
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=5)
    Session(app)
    
    CORS(app, supports_credentials = True, resources={r"/webapp/*": {"origins": "http://localhost:3000/"}})
    
    @app.route("/webapp/login", methods = ["POST"])
    def login():
    
        user = request.get_json(force=True)
    
        Email = user.get("email", "")
        Password = user.get("password", "")
    
        login = Login.login(Email, Password)
    
        if login["Success"]:
    
            session["email"] = Email
    
        return login
    
    @app.route("/webapp/checksession", methods = ["GET"])
    def checksession():
    
        sessionEmail = session.get("email", "")
    
        if sessionEmail == "":
    
            return utils.returnResult(False, "Session not valid")
    
        return utils.returnResult(True, "")

And in the React app I use axios to do the login and check the session in the server, for example:

    axios.get(APIURL + CHECK_SESSION, {withCredentials: true})
    .then(response => {
    
        console.log(response.headers);
        
        setSession(response.data.success)
        setCheckedSession(true)
        
    })
    .catch(err => {
    
        setSession(false)
        setCheckedSession(true)
    
        if(err.response) {
    
        }
        else {
    
            window.alert('Could not establish a connection to the server!');
        }
    });

In the dev tools we can see that the server is sending the cookie session:

enter image description here

But when I check the cookies for the app there’s nothing there:

enter image description here
(Sorry for the Portuguese)

And in the axios promise handler, when I print the headers of the response, this is all I get:

enter image description here

So every time the react app checks if the user has a valid session in the server, the server creates a new session, which means that the react app is not saving and sending the cookie to the server.

Also, when I test this with postman everything works fine.

I searched all over the places and I can’t find an answer for this. Can anyone help me figure out what I’m doing wrong, please?

Solution

Turns out it was missing configurations in the flask session:

app.config["SESSION_COOKIE_SAMESITE"] = "None"
app.config["SESSION_COOKIE_SECURE"] = True

Answered By – João Amaral

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published