Code Monkey home page Code Monkey logo

csrf's Introduction

Nestjs CSRF token validator

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

or

$ yarn add ncsrf

Usage

Import in main.ts to enable the middleware globally

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;

How to verify csrf token

HTTP Request must be have at least one of these headers:

  • csrf-token
  • xsrf-token
  • x-csrf-token
  • x-xsrf-token
    or query param:
  • _csrf
    or body param:
  • _csrf

Restful API Setup

Important: Request must be sent with withCredentials set to true to allow cookies to be sent from the frontend or credentials set to include in fetch API.

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!";
  }

Protected route with csrf and custom exception message

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

GraphQL Setup

Important: Request must be sent with withCredentials set to true to allow cookies to be sent from the frontend or credentials set to include in fetch API.

Generate token here

  @Query((returns) => string, { name: 'getToken', nullable: false })
  async getUsers(@Context('req') req: any) {
    return req?.csrfToken();
  }

Protected route with csrf

  import {CsrfQL} from "ncsrf";
  ...
  @Mutation((returns) => string, { name: 'needProtect', nullable: false })
  @CsrfQL()
  needProtect(): string{
    return "Protected!";
  }

Protected route with csrf and custom exception message

  import {CsrfQL} from "ncsrf";
  ...
  @Mutation((returns) => string, { name: 'needProtect', nullable: false })
  @CsrfQL("Custom exception message")
  needProtect(): string{
    return "Protected!";
  }

Issue & contribute

  • If you have any issue, please create an issue.
  • If you want to contribute, please create a pull request.

Thank you for using this module.

csrf's People

Contributors

andonguyen avatar huy97 avatar rikkei-huylt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

csrf's Issues

Invalid CSRF Token

Hello, im using your package, when i try with postman it works but if send requests from angular im getting Invalid CSRF Token

Question

Should the backend have Get /token endpoint. Isn't that against the csrf not have a endpoint for grabbing the token.

If not how does the frontend get the token, the secret is correctly set in cookies.

Update dependencies to work with nestjs 9.0.0 and newer.

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: @nestjs/[email protected]
npm ERR! node_modules/@nestjs/common
npm ERR!   @nestjs/common@"^9.0.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer @nestjs/common@"^8.4.4" from [email protected]
npm ERR! node_modules/ncsrf
npm ERR!   ncsrf@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

update the peer Dependencies to the latest versions

The peer dependencies used in the package are older versions. It will be good to update to the newest version so that there will be no conflict withe the versions.

"rxjs": "^6.6.3" => "rxjs": "^7.5.5",
"@nestjs/common": "^7.6.1", => "@nestjs/common": "^8.4.4",

_csrf token not generate in new request

I used the ncsrf token and the _crsf token get validated only in the first request and the rest got forbidden I think it because the _csrf token not changed

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.