[Python] Flask-JWT-Extended: Unauthorized on @jwt_required() Despite Cookie Being Set

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    'm using Flask-JWT-Extended to handle authentication in my Flask backend, and I'm storing JWT tokens in HttpOnly cookies. The login process successfully sets the access_token_cookie in the browser, and I can see it in the Application → Cookies section in Chrome DevTools.

    However, when I make a request to an endpoint protected with @jwt_required(), I get an Unauthorized (401) error.

    Backend (Flask ):

    `@shop_bp.route("/signin", methods=['POST'])
    def shop_login():
    try:
    data = request.json
    shop =
    Shop.query.filter_by(shop_phone=data['shop_number']).first()

    if shop and shop.password == data['password']:
    access_token = create_access_token(identity=f'shop:{shop.id}')

    response = jsonify({"message": True})
    print(response)
    response = make_response(jsonify({"message": True}))

    print(response)
    set_access_cookies(response, access_token)

    return response
    return jsonify({'message': False}), 401
    except Exception as e:
    print("Error in ShopSignIn:", str(e))
    print(traceback.format_exc())
    return jsonify({"error": "Internal Server Error"}), 500`


    Frontend Request (Vue.js, Axios):

    `actions: {
    async checkAuthStatus() {
    try {
    const response = await axios.get('http://127.0.0.1:5000/auth/check_login_status', {
    withCredentials: true,
    headers: { "Content-Type": "application/json" }
    });
    this.isShopLoggedIn = true;
    if (response.data.logged_in) {

    return this.userId;
    } else {
    this.resetAuthState();
    }
    } catch (error) {
    console.error('Auth check failed:', error);
    this.resetAuthState();
    }
    },`


    Issue: Login works fine, and the access_token_cookie is visible in browser cookies. When calling /auth/check_login_status, it returns a 401 Unauthorized instead of recognizing the token. The token does not seem to be sent in the request headers.

    What I’ve Tried: Verified that cookies are being set in the browser. Ensured withCredentials: true is included in Axios requests. Changed JWT_COOKIE_SAMESITE from "Strict" to "Lax". Set CORS(supports_credentials=True) in Flask. Checked for any conflicting set-cookie headers in responses.

    Expected Behavior: When sending a request to /auth/check_login_status, the stored cookie should be sent automatically, allowing @jwt_required() to recognize the user.

    Question: Why is the access_token_cookie not being sent in the request, or why is Flask-JWT-Extended not recognizing it? How can I fix this issue?

    Continue reading...

Compartilhe esta Página