[Python] Request from React app to Flask server not including cookies

Discussão em 'Python' iniciado por Stack, Dezembro 21, 2024.

  1. Stack

    Stack Membro Participativo

    I'm trying to send a get request with cookies from my React app to Flask server. Both are locally hosted with different origin.

    Request from react:

    export async function fetchUser() {
    try {
    const res = await fetch(`${BASE_URL}/user`, {
    method: 'GET',
    credentials: 'include',
    });
    if (res.ok) {
    const data = await res.json();
    return data.user; // or wtv format it is
    } else {
    const data = await res.json();
    console.log(data)
    return null
    }
    } catch (error) {
    console.error(error);
    return null
    }



    Flask app:

    app = Flask(__name__)
    CORS(app, supports_credentials=True, resources={r"/*": {"origins": ['http://localhost:5173']}})

    def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
    token = request.cookies.get('token', 0) # Get the token from cookies
    print(token)
    if token is 0:
    return jsonify({'message': 'Token is missing!'}), 401
    result = enc.validate_token(token)
    if not result['success']:
    return jsonify({'message': result['message']}), 401
    identity = result['identity']
    return f(identity, *args, **kwargs)
    return decorated

    @app.route("/user", methods=['GET'])
    @token_required
    def get_user(current_user):
    if not current_user:
    return jsonify({'error': 'User not found!'}), 404
    return current_user

    @app.route("/login", methods=['POST'])
    def login():
    data = request.get_json()
    username = data['username']
    password = data['password']
    login = au.handle_login(username, password)
    if login['success']:
    response = make_response(jsonify({ 'success': login['success'], 'message': login['message'] }), 200)
    response.set_cookie(
    "token",
    value=login['token'],
    expires=login['expires'],
    max_age=login['max_age'],
    httponly=True, # Prevent JavaScript access
    secure=False, # TRUE: Only over HTTPS in production
    samesite="Lax" # STRICT: Protect against CSRF
    )
    return response, 200
    return jsonify(login), 401



    The cookie is set from the same flask server through a different route, and the application cookies tab shows that it's there with the correct key token. I've added credentials: 'include' in the request and supports_credentials=True in the flask CORS config, but in the /user route, request.cookies.get('token') is returning None.

    Nothing seems out of place and I've ran out of ideas to try - if anyone can help figure out what's up I'd be so grateful

    Continue reading...

Compartilhe esta Página