javascript - 使用访问/刷新令牌和 axios(cookies?本地存储?)进行安全身份验证
问题描述
我正在使用 nodejs 后端构建一个具有访问和刷新令牌的身份验证系统。
目前,我只使用有效期为 24 小时的访问令牌。我将它们设置在服务器上的 httpOnly-cookie 中,仅通过 https 发送(安全:true)。使用 axios,我将 withCredentials-option 添加到请求中,并将 cookie(带有令牌)发送到服务器。
我对 axios 进行了一些调整以使用访问/刷新令牌。到目前为止我的代码:
import axios from 'axios';
const apiUrl = 'http://localhost:5000/api',
// add the accessToken to the request config when making a request
// with axios
axios.interceptors.request.use((config) => {
const accessToken = localStorage.getItem('accessToken');
if (accessToken) {
config.headers['Authorization'] = `Bearer ${accessToken}`;
}
return config;
}, (error) => {
return Promise.reject(error);
});
// check if a status 401 is send back
// this means the access token is invalid
// do a request to the server to refresh the access token with the refresh token
// and repeat the initial request when the new access token is received
axios.interceptors.response((response) => {
// status 200 OK
// just return the response
return response;
}, (error) => {
// store the original request (passed with the error)
const origReq = error.config;
const refreshToken = localStorage.getItem('refreshToken');
// origReq.retried is just to prevent an infinite loop of retries
if (refreshToken && !origReq.retried) {
origReq.tried = true;
return axios({
method: 'get',
url: `${apiUrl}/auth/refresh-access-token`,
headers: {
'Authorization': `Bearer ${refreshToken}`
}
})
.then((response) => {
// store the new access token
localStorage.setItem('accessToken', response.data.accessToken);
// retry the original request
return axios(origReq);
});
} else {
return Promise.reject(error);
}
);
基本上我创建了 2 个拦截器:1 个用于请求(将访问令牌添加到请求)和 1 个用于响应(检查响应状态,如果状态 = 401 则访问令牌无效,因此请先刷新访问令牌使用刷新令牌)。
关于此代码的一些注意事项:
- 在生产环境中,对 API 的所有请求都将通过 HTTPS 进行。
- 将访问/刷新令牌放入 Authorization-header 可以吗?在一些代码示例中,我看到他们将刷新令牌放在 POST 正文中。什么是最有效/最安全的方式?在我的代码中,我检查了 Authorization-header 并且这有效,但我想知道什么是最好的。
- 在此代码示例中,我将访问和刷新令牌存储在LocalStorage中。我找到了这篇中型文章,但我看不懂,它应该包含有关如何安全存储令牌的信息。这篇文章说 JWT 令牌(就像我用于访问/刷新令牌一样)应该存储在 httpOnly cookie 中,就像我现在做的那样?但是如何在我的 axios 请求中注入 httpOnly-cookies 的值呢?我知道它有效
with withCredentials: true
,但是每次请求都会发送访问和刷新令牌吗?也许响应拦截器已经过时了,因为当访问令牌无效时,我可以直接在服务器上检查刷新令牌。 - 如果我是正确的,当我通过 Authorization-header ( source -> first answer)发送我的令牌时,我不需要明确的 CSRF 保护。但是当我切换到带有
withCredentials: true
标题的 httpOnly-cookies 时,我确实需要它,对吗?
提前致谢!
解决方案
推荐阅读
- ibm-odm - 决策中心——决策治理框架
- reactjs - material-ui v4.11.1 - 不能给函数组件提供参考。尝试访问此 ref 将失败。你的意思是使用 React.forwardRef() 吗?
- android - 在支持 AR 的设备中创建 AR 会话失败
- jquery - node.js:给出绝对路径后,打印整个js而不是加载网站
- javascript - 从嵌套数组对象中查找对象
- python-3.x - 不同目录中的2个python二进制文件之间的区别
- ms-access-2010 - 检查子表单上的 .NewRecord 属性 - 无效参考
- c# - ASP.NET 如何在不删除以前数据的情况下向数据库单元添加其他数据
- node.js - 协议错误 - html-pdf-node npm 包
- spring-boot - 我的 Spring Boot 应用程序要么重定向到 Spring Security 登录页面,要么显示白标错误