如何使用Axios将CSRF令牌发送回服务器



我有一个Express Server,它有一个为客户端生成csrf令牌的端点

现在,我尝试在我的axios请求中发送回令牌,如下所示,但我一直收到常见的Forbidden:无效的csrf令牌错误。

以下是我的代码:

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令牌,还必须包含与对先前axios.get请求的响应一起接收的cookie。您的代码只设置标头。除非axios自动处理cookie(就像浏览器一样(,否则还必须包含用于处理cookie的客户端代码。

最新更新