简体   繁体   English

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

[英]How to send back CSRF Token to server with Axios

I have an Express Server with an endpoint that generates the csrf token for the client,我有一个带有端点的 Express Server,可以为客户端生成 csrf 令牌,

Now, I tried sending back the token in my axios request as below but I keep getting the usual Forbidden: invalid csrf token error.现在,我尝试在我的 axios 请求中发回令牌,如下所示,但我一直收到通常的 Forbidden: invalid csrf token 错误。

Below is my code:下面是我的代码:

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));
    });
}

But the server still keeps throwing the usual:但是服务器仍然不断抛出通常的:

ForbiddenError: invalid csrf token ForbiddenError:无效的 csrf 令牌

Here is a snippet into my server setup这是我的服务器设置中的一个片段

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() });
       });
....

Because of csrf({cookie: true}) , the CSRF token is bound to a cookie.由于csrf({cookie: true}) ,CSRF 令牌绑定到 cookie。 The axios.post request must contain not only the CSRF token in a header, but also the cookie that was received with the response to the previous axios.get request. axios.post请求不仅必须在标头中包含 CSRF 令牌,还必须包含响应前一个axios.get请求而收到的 cookie。 Your code sets only the header.您的代码仅设置标题。 Unless axios handles the cookies automatically (like a browser would do), you must include client-side code for handling them as well.除非axios自动处理 cookie(就像浏览器那样),否则您还必须包含客户端代码来处理它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM