Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS CSRF for specefic controller route

I want to use csrf only for a controller not whole of application.

@UsePipes(new CsrfPipe())
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
import * as csrf from 'csurf';

@Injectable()
export default class CsrfPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    if (metadata.type == 'body') {
      const csrfProtection = csrf({ cookie: true });
      csrfProtection(); // what shall I do here ?
    }

    return value;
  }
}

like image 273
Daniel Dez Avatar asked Jan 31 '26 17:01

Daniel Dez


1 Answers

Try this one

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    //Apply csrf for specific routes
    consumer.apply(csrf({ cookie: true })).forRoutes(
      { path: 'auth/login', method: RequestMethod.POST },
      {
        path: 'auth/csrf',
        method: RequestMethod.GET,
      },
    );
  }
}
like image 154
ndc1509 Avatar answered Feb 02 '26 10:02

ndc1509