I face an issue when I am using csrf-csrf
to replace csurf
. The token was generated successfully. But once I submit a form, it shows the error invalid csrf token
:
My code:
in app.js
app.use((req, res, next) => {
res.locals.isAuthenticated = req.session.isLoggedIn;
res.locals.csrfToken = generateToken(res);
console.log(res.locals.csrfToken);
next();
});
in view:
<form class="login-form" action="/signup" method="POST">
...
<input type="hidden" name="_csrf" value="<%= csrfToken %>" >
<button class="btn" type="submit">Signup</button>
</form>
When I click Signup. the error shows up.
ForbiddenError: invalid csrf token
at doubleCsrf (/workspace/nodejs-practice/node_modules/csrf-csrf/lib/cjs/index.cjs:18:61)
at Object.<anonymous> (/workspace/nodejs-practice/app.js:24:5)
at Module._compile (node:internal/modules/cjs/loader:1165:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1219:10)
at Module.load (node:internal/modules/cjs/loader:1043:32)
at Function.Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:22:47
Any idea about this? Thank you guys!
update:
I checked the source code of csrf-csrf
. I find out it gets the token from request by
getTokenFromRequest = (req) => req.headers["x-csrf-token"]
In my case, it will be undefined. So how can I add the token into the request headers?
I solve this issue by rewrite the getTokenFromRequest
in doubleCsrf().
const {
generateToken, // Use this in your routes to provide a CSRF hash cookie and token.
doubleCsrfProtection, // This is the default CSRF protection middleware.
} = doubleCsrf({
getSecret: () => "my secret",
getTokenFromRequest: (req) => {
return req.body._csrf;
},
});
I have to say I still have a long way to go to be a good developer.
Hope this helps others.
Don't be afraid to read the source code, maybe you'll find it's not as mysterious and difficult to understand as you thought
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.