node.js - 如何使用 Axios 将 CSRF Token 发送回服务器
问题描述
我有一个 Express 服务器,其端点为客户端生成 csrf 令牌,
现在,我尝试在我的 axios 请求中发回令牌,如下所示,但我不断收到通常的 Forbidden: invalid csrf token 错误。
下面是我的代码:
static async attachCSRFTokenToHeaders(headers) {
let csrfTokenRequest = await axios.get(EndPoints.CSRF_TOKEN);
let csRefToken = csrfTokenRequest.data;
headers['X-CSRF-TOKEN'] = csRefToken.csrfToken;
}
static async getRequestHeaders() {
let headers = {};
//Possibly add more headers
await this.attachCSRFTokenToHeaders(headers); //Attach the csrf token to the headers of each request
return headers;
}
static async logInManually(email, password, cb) {
let requestBody = { email, password};
axios.post(EndPoints.SIGN_IN, requestBody, {
headers: await this.getRequestHeaders() //Attach the headers here
}).then((response) => {
cb(HttpSuccessDataHandler.getSuccessResponseData(response), null);
}).catch((e) => {
cb(null, HttpErrorHandler.spitHttpErrorMsg(e));
});
}
但是服务器仍然照常抛出:
ForbiddenError: 无效的 csrf 令牌
这是我的服务器设置的一个片段
const csrf = require('csurf');
const cookieParser = require('cookie-parser');
const session = require('express-session');
....
initMiddleWare() {
app.use(express.static('./static'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser())
app.use(session({
secret: Constants.SESSIONS_SECRET,
resave: false,
saveUninitialized: false
}));
app.use(busboy({
highWaterMark: 2 * 1024 * 1024,
limits: {
fileSize: maxFileSize,
}
}));
app.use(csrf({ cookie: true }))
}
//Then somewhere in my routes, here is the route that provides the csrf token
.....
app.get(Routes.CSRF_TOKEN, function (req, res) {
res.send({ csrfToken: req.csrfToken() });
});
....
解决方案
由于csrf({cookie: true})
,CSRF 令牌绑定到 cookie。axios.post
请求不仅必须包含标头中的 CSRF 令牌,还必须包含与前一个请求的响应一起收到的cookie axios.get
。您的代码仅设置标题。除非axios
自动处理 cookie(就像浏览器那样),否则您还必须包含用于处理它们的客户端代码。
推荐阅读
- c# - EF Core 关系 - 冗余列 ID
- google-maps - Google 在 Maps Time Zone API 配额中所说的“用户”是什么意思?
- javascript - Firestore 中的数据未更新
- sql - SQL 排除 NULL 或值 0
- eclipse - Eclipse:如何使用 dropins 目录进行低级安装
- react-native - 如何将导航参数发送到测试
- javascript - 对象文件名在 Firefox 上包含 ':' 路径分隔符
- asp.net-core-mvc - ASP.NET MVC Core 中的路由,标签助手路由到错误的 POST 操作
- docker - 如何在 docker 容器中安装主管?
- xmpp - Smack 在 Roster 的存在监听器中抛出 NullPointerException