And*_*rew 5 cookies fetch express jwt redux
我已经阅读了我可以找到的所有其他主题,但没有一个解决方案有效.我使用React + Redux + Express并尝试按照以下方式将JWT存储在cookie中:
https://auth0.com/blog/2015/09/28/5-steps-to-add-modern-authentication-to-legacy-apps-using-jwts/
在我的Redux操作中,我发送以下请求:
export function getCookie(token) {
const config = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
body: JSON.stringify({ token })
};
return fetch('http://127.0.0.1:4000/authorize-cookie', config)
.then((res) => {
return res.json();
})
.then((resJson) => {
return resJson;
})
.catch(err => console.log('Error: ', err));
}
Run Code Online (Sandbox Code Playgroud)
在服务器上,我正在回复...
app.post('/authorize-cookie', authenticate, (req, res) => {
res.cookie('id_token', req.body.token, {
maxAge: 360000
});
res.status(200).send({ message: 'Cookie set!' });
});
Run Code Online (Sandbox Code Playgroud)
... authenticate是一个验证令牌的函数.
我的响应标题似乎一切都很好:
HTTP/1.1 200 OK
Set-Cookie: id_token=xxx.xxx.xxx; Max-Age=360; Path=/; Expires=Tue, 12 Jan 2016 01:24:03 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 25
ETag: W/"19-UA3htFr0PWczMQBN6T4NpA"
Date: Tue, 12 Jan 2016 01:18:03 GMT
Connection: keep-alive
Run Code Online (Sandbox Code Playgroud)
但是当我查看"源"选项卡时,找不到cookie.我已经读过关于关闭httpOnly和安全以及使用localhost的问题.我也尝试过每一个主要的浏览器,没有运气.
这里发生了什么?
jus*_*ris 13
你遇到了一个有趣的案例.事实是fetch
功能的行为是不同的而不是XMLHttpRequest
.要使用cookie,fetch
您应该明确提供credentials
选项.
fetch('http://127.0.0.1:4000/authorize-cookie', {
method: 'POST',
body: JSON.stringify({token: token}),
credentials: 'same-origin', // <- this is mandatory to deal with cookies
})
Run Code Online (Sandbox Code Playgroud)
凭据:要用于请求的请求凭据:省略,同源或包含.要自动发送当前域的cookie,必须提供此选项.
归档时间: |
|
查看次数: |
3203 次 |
最近记录: |