1.0.0 • Published 3 years ago

nestjs-csrf v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

@nestjs/csrf

Table of Contents

About

Nestjs CSRF protection middleware. If you have questions on how this module is implemented, please read Understanding CSRF.

Prerequisites

Requires either a session middleware or cookie-parser to be initialized first, and need enableCors.

  app.use(cookieParser());

Installing

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install ncsrf --save

Usage

Import in main.ts and enable

  import {nestCsrf, CsrfFilter} from 'ncsrf';
  import cookieParser from 'cookie-parser';

  app.use(cookieParser());
  app.use(nestCsrf());

nestCsrf(options)

  • signed - indicates if the cookie should be signed (defaults to false).
  • key - the name of the cookie to use to store the token secret (defaults to '_csrf').
  • ttl - The time to live of the cookie use to store the token secret (default 300s).

Custom exception message

  app.useGlobalFilters(new CsrfFilter);

Or use your custom exception filter by catch 2 class

  CsrfInvalidException

And

  CsrfNotFoundException

Example

Generate token here

  @Get('/token')
  getCsrfToken(@Req() req): any {
    return {
      token: req.csrfToken()
    }
  }

Protected route with csrf

  import {Csrf} from "ncsrf";
  ...
  @Post()
  @Csrf()
  needProtect(): string{
    return "Protected!";
  }
1.0.1

3 years ago

1.0.0

3 years ago