'How do I persist auth between react and a flask server

I created a flask server and added the following endpoints to this server:

@auth_routes.route('/login', methods=['POST'])
def log_in():
    log_in_data = request.get_json()
    user = User.query.filter(User.email == log_in_data['email']).first()

    if (not any([user])):
        return {'message': 'invalid email'}, 401
    if not user.check_password(log_in_data['password']):
        return {'message': 'invalid password'}, 401

    login_user(user)
    return {'message': 'success'}

@auth_routes.route('/logged_in')
def logged_in():
    return {'logged in': current_user.is_authenticated}

When I hit the /login endpoint and then the /logged_in endpoint via postman, I see that the login has persisted. but if I do the same thing with react, by using axios it is not persisted.

On the backend I am using flask_login to manage the authentication.

I'm not getting any error messages, however this is not what I am intending. I am trying to get the code to persist the login on the backend - but this only works when I use postman and not react.

This is the function that is invoked on the front-end.

const loginFunc = async () => {
        const result = await axios.post('http://127.0.0.1:5000/auth/login', {email, password})
        const loggedin = await axios.get('http://127.0.0.1:5000/auth/logged_in')
        console.log(result, loggedin)
    }

I thought that the flask_login would completely handle the session / authentication, but it doesn't seem to persist it. Am I missing something? Am I also supposed to send something over with the request when I am using flask_login?



Solution 1:[1]

const loginFunc = async () => {
        const result = await axios.post('http://127.0.0.1:5000/auth/login', {email, password}) <—- this post request needs {withCredentials: true}
        const loggedin = await axios.get('http://127.0.0.1:5000/auth/logged_in') <—- same here
        console.log(result, loggedin)
    }

Try:

   const loginFunc = async () => {
        const result = await axios.post('http://127.0.0.1:5000/auth/login' {withCredentials: true}, {email, password})
        const loggedin = await axios.get('http://127.0.0.1:5000/auth/logged_in', {withCredentials: true})
        console.log(result, loggedin)
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nerdtown