首页 > 解决方案 > 无法使用 Flask-JWT-Extended、React 和 Axios 在 Chrome 中设置 cookie

问题描述

背景和问题

我有一个在 localhost:5000 上运行的 Flask 后端和一个在 localhost:3000 上运行的 React SPA。console.log(response)我能够让他们说话,但是当尝试将 Flask 生成的令牌存储到浏览器的 cookie 中时 1) 响应标头在成功 POST 之后执行时不包含任何 cookieaxios并且 2) 没有设置 cookie。但是当检查 network > Login.js 标头时,我实际上可以看到Set-Cookie密钥作为响应的标头存在。我尝试了 Google 和 StackOverflow 的多种解决方案,但似乎没有解决方案在这里有效,我真的无法弄清楚请求成功发出后发生了什么,并且 Chrome 允许第三方软件设置 cookie。甚至我也可以从 Network > Login.js 标头中看到令牌。

脚步

1)用户输入他们的用户名和密码并点击登录。

2) 对 Flask 的后端进行 Axios POST 调用。

3)处理数据并生成几个令牌并将它们设置为cookie。

4) 浏览器的 cookie 设置的令牌很少。<- 这部分不起作用。

代码

Flask 后端令牌生成使用flask-jwt-extended

# app_config related to flask-jwt-extended
CORS_HEADERS = "Content-Type"
JWT_TOKEN_LOCATION = ["cookies"]
JWT_COOKIE_SECURE = False
JWT_COOKIE_CSRF_PROTECT = True



# post method from flask-restful for LoginAPI class
def post(self):
    email = request.json.get("email")
    password = request.json.get("password")

    # some processing here.....
    payload = {
        "email": email
    }

    access_token = create_access_token(identity=payload)
    refresh_token = create_refresh_token(identity=payload)

    response = jsonify({"status": True})
    set_access_cookies(response, access_token)
    set_refresh_cookies(response, refresh_token)

    return response

CORS 使用flask-cors

# in below code, I had some issues with putting wildcard (*) into origin, so I've specified to the React SPA's host and port.
CORS(authentication_blueprint, resources={r"/authentication/*": {"origins": "http://localhost:3000"}},
     supports_credentials=True)

React SPA - 使用axios

# also tried `axios.defaults.withCredentials = true;` but same result.
export const login = (email, password, cookies) => {
return dispatch => {
    const authData = {
        email: email,
        password: password
    };

    let url = 'http://127.0.0.1:5000/authentication/login/';

    axios.post(url, authData, {withCredentials: true)
        .then(
            response => {
                console.log(response)
            })
        .catch(err => {
            console.log(err)
        });

    dispatch(authSuccess(email, password));
    }
};

下图是成功后调用的响应axios 我不确定这是否正常,但响应的标头没有显示我从后端设置的任何 cookie。

在此处输入图像描述

下图来自网络>登录标题/

如图,可以清楚的看到带Set-Cookiekey的token信息。我还检查过它们不是secure

在此处输入图像描述

最后,当我从应用程序 > cookie 检查我的 cookie 选项卡时,我什么也没看到。

标签: reactjsflaskcookiesaxioscross-domain

解决方案


所以问题来自localhost.

我有一个在 localhost:5000 上运行的 Flask 后端和一个在 localhost:3000 上运行的 React SPA。

从上面的陈述来看,具体来说,我在 localhost:5000 上运行后端并在 127.0.0.1:3000 上运行 React SPA。

一旦我改变了127.0.0.1to localhost,它就像一个魅力。

附带说明一下,在玩过之后CORS,我认为它会更容易使用Nginx并将proxy_pass来自 React SPA 的请求传递到后端以避免CORS完全使用,因为如果必须CORS在不同的环境中使用,例如测试,登台等,无论如何都必须CORS在Web服务器级别进行设置,例如)Nginx它需要的配置与我为本地环境设置的方式略有不同。


推荐阅读