Fastify Csrf Protection with @fastify/session plugin
- Dominant language
- No language data
- Stars
- 68
- Forks
- 8
- Avg merge
- 11h 2m
- Merged PRs (30d)
- 2
Description
#### You have already researched for similar issues?
Yes, I have also reached out multiple times on the fastify discord.
#### What are you trying to achieve, or the steps to reproduce?
I am attempting to use the csrf-protection plugin in my application. The issue I am having is with the internal csrfProtection function. Included here I added a couple logging statements.
```js
function csrfProtection (req, reply, next) {
const secret = getSecret(req, reply)
if (!secret) {
req.log.warn('Missing csrf secret')
return reply.send(new MissingCSRFSecretError())
}
if (!tokens.verify(secret, getToken(req), getUserInfo(req))) {
req.log.warn('Invalid csrf token')
req.log.warn({ token: getToken(req), secret: secret, userInfo: getUserInfo(req) });
req.log.info(`Verify: ${tokens.verify(secret, getToken(req), getUserInfo(req))}`);
return reply.send(new InvalidCSRFTokenError())
}
next()
}
```
I can confirm that the value from getToken and the secret from getSecret are exactly the same. However it is still failing the verify method. I am not sure what I am missing. Here is my test route,
```js
fastify.post('/test', {
onRequest: fastify.csrfProtection,
// onRequest: function (request, reply, done) {
// const csrf = request.unsignCookie(request.cookies['xsrf]);
// if (!request.session.user) {
// reply.code(403).send({ error: 'Unauthorized' });
// } else if (!csrf.valid || csrf.value !== request.session._csrf) {
// reply.code(403).send({ error: 'Invalid CSRF token' });
// } else {
// done();
// }
// },
}, async function (request, reply) {
return { message: 'Hello world' };
});
```
The commented out method works, but the decorated method doesn't
#### Context
* *node version*: 20
* *fastify version*: >=4.24.3
* *@fastify/csrf-protection*: ^6.3.0
* *@fastify/session*: ^10.5.0
* *@fastify/cooki*: ^9.1.0
* *os*: Windows
Contributor guide
Assessment
This issue has not been assessed yet.