CSRF with fastify session cookies

Viewed 639

I have a fastify session plugin that creates user sessions and manages them in postgres, but i want to make sure that i have all my sessions protected from CSRF. Im looking at the fastify-csrf plugin and im not exactly sure how to properly implement this. Do i need to generate the csrf token only when the session cookie is first generated or on all requests?

session plugin:

const cookie = require('fastify-cookie');
const session = require('fastify-session');
const csrf = require('fastify-csrf');
const pgSession = require('connect-pg-simple')(session);
const fp = require('fastify-plugin');

/**
 * @param {import('fastify').FastifyInstance} fastify
 */
const plugin = async (fastify) => {
  // All plugin data here is global to fastify.
  fastify.register(cookie);
  fastify.register(csrf, { sessionPlugin: 'fastify-session' });
  fastify.register(session, {
    store: new pgSession({
      conString: process.env.DATABASE_URL,
      tableName: 'user_session', // Defaults to 'session'
    }),
    secret: process.env.SESSION_SECRET,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      secure: process.env.NODE_ENV !== 'development',
      maxAge: 86400 * 1000, // 1 day expiration time
    },
  });

  <!--  This is from the documentation, should this only be applied to the /login route when the cookie is generated? When do i verify that the cookie has not been tampered with?
  fastify.route({
    method: 'GET',
    path: '/',
    handler: async (req, reply) => {
      const token = await reply.generateCsrf();
      return { token };
    },
  });

  // Add the user object to the session for later use.
  fastify.addHook('preHandler', (req, reply, next) => {
    if (!req.session) req.session.user = {};
    next();
  });
};

module.exports = fp(plugin);
0 Answers
Related