fastify / csrf-protection

A fastify csrf plugin.
Other
151 stars 19 forks source link

CSRF route protection example given in README not working #131

Closed ganjarsetia closed 1 year ago

ganjarsetia commented 1 year ago

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

const fastify = require('fastify')({ logger: true });

fastify.register(require('@fastify/cookie'));
fastify.register(require('@fastify/csrf-protection'));

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

fastify.listen({ port: 3000 }, function (err, address) {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
});

I'm want to use CommonJS style, not ESM.

Expected Behavior

It should show some kind error like "Missing CSRF token".

mcollina commented 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;
  },
});

})