csrf-guard
Simple Anti-CSRF Token implementation for Express applications.
This package only uses Node.js native crypto module and no other dependency. I did my best to follow OWASP CSRF token best practices. Now it's your responsibilty to follow best practices for session management. I do recommend you read this article before anything else.
Disclaimer: This package is still under development, I do NOT recommend using it for production yet.
Installation
npm:
npm install csrf-guard
yarn:
yarn add csrf-guard
GitHub:
git clone https://github.com/venomaze/csrf-guard.git
Usage
First register the middleware:
const express = ;const session = ;const CSRFGuard = ; const app = ; // DO NOT USE SESSION LIKE THIS!app; app;
Then you have access to two getToken
and isTokenValid
methods from request object.
- Generating a token (Remember you have to use csrf_token name for the token):
app;
- Validating the token:
app;
Token generation methods
We have to options, the first one is Synchronizer Token Pattern and the second one is HMAC Based Token Pattern. You can read more about them here.
Synchronizer Token Pattern
To be able to use this method, you have to set synchronizer
to true
in options object. With this method you have access to forced
mode which generates a new token even if there is one already. This is the default method.
Setting up:
app;
Generating token:
const token = await req; // Forced is set to true. This way you'll get a new token per request. (Default to false)
HMAC Based Token Pattern
To be able to use this method, you have to set synchronizer
to false
in options object. With this method you have access to expiryTime
option which gives you this possibility to expire tokens even if the session id isn't changed. By default, tokens won't be expired until the session is regenerated.
Setting up:
app;
Generating token:
const token = req;