【发布时间】:2020-08-26 10:25:55
【问题描述】:
背景和问题
我有一个在 localhost:5000 上运行的 Flask 后端和一个在 localhost:3000 上运行的 React SPA。
我能够让他们说话,但是当尝试将 Flask 生成的令牌存储到浏览器的 cookie 中时 1)在从 axios 成功发布后执行 console.log(response) 时响应标头不包含任何 cookie 和 2)cookie 不是放。但是在检查 network > Login.js 标头时,我实际上可以看到 Set-Cookie 键作为响应的标头存在。我尝试了 Google 和 StackOverflow 的多种解决方案,但似乎没有解决方案在这里有效,我真的无法弄清楚请求成功发出后发生了什么,并且 Chrome 允许第三方软件设置 cookie。甚至我可以从 Network > Login.js 标头中看到令牌。
步骤
1) 用户输入他们的用户名和密码并点击登录。
2) 对 Flask 的后端进行 Axios POST 调用。
3) 处理数据并生成几个令牌并将它们设置到 cookie 中。
4) 浏览器的 cookie 设置有少量标记。
代码
使用flask-jwt-extended 生成Flask 后端令牌
# 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-Cookie键可以清楚的看到token信息。我还检查了他们不是secure。
最后,当我从应用程序 > cookie 检查我的 cookie 选项卡时,我什么也没看到。
【问题讨论】:
-
如果我是你,我会在 json 响应中发送令牌并在前端设置 cookie。如果不使用 UI 来处理请求,那么 api 会更干净。
标签: reactjs flask cookies axios cross-domain