首页 > 解决方案 > 如何使用 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() });
       });
....

标签: node.jsexpressaxios

解决方案


由于csrf({cookie: true}),CSRF 令牌绑定到 cookie。axios.post请求不仅必须包含标头中的 CSRF 令牌,还必须包含与前一个请求的响应一起收到的cookie axios.get。您的代码仅设置标题。除非axios自动处理 cookie(就像浏览器那样),否则您还必须包含用于处理它们的客户端代码。


推荐阅读