在rails中,默认会话存储使用cookie.会话被封送并使用密钥签名,以便客户端无法使用它进行调整.这种方法非常可扩展,不需要任何类型的"后端"工作.
对于Express或Connect,我找不到类似的东西.
我已经阅读了我可以找到的所有其他主题,但没有一个解决方案有效.我使用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; …Run Code Online (Sandbox Code Playgroud)