Closed ganjarsetia closed 1 year ago
Wrap your routes in a plugin:
const fastify = require('fastify')({ logger: true });
fastify.register(require('@fastify/cookie'));
fastify.register(require('@fastify/csrf-protection'));
fastify.register(async function (fastify) {
// generate a token
fastify.route({
method: 'GET',
path: '/',
handler: async (req, reply) => {
const token = await reply.generateCsrf();
return { token };
},
});
// protect a route
fastify.route({
method: 'POST',
path: '/',
onRequest: fastify.csrfProtection,
handler: async (req, reply) => {
return req.body;
},
});
})
Prerequisites
Fastify version
4.15.0
Plugin version
6.2.0
Node.js version
18.14.0
Operating system
Linux
Operating system version (i.e. 20.04, 11.3, 10)
Ubuntu 22.04.2 LTS
Description
I followed the sample code which is in the README. Using cookie version. I called the protected route without generate CSRF token, but as a result I can still access it. That's not what we want.
Steps to Reproduce
npm init -y
yarn add fastify @fastify/cookie @fastify/csrf-protection
index.js
and add code belownode index.js
http://localhost:3000/
using Postman or curl likecurl --request POST --url http://localhost:3000/ --header 'content-type: application/json' --data '{ "hello": "world" }'
I'm want to use CommonJS style, not ESM.
Expected Behavior
It should show some kind error like "Missing CSRF token".