What is csrf?
The csrf npm package is used to generate and validate CSRF (Cross-Site Request Forgery) tokens to protect web applications from CSRF attacks. It is commonly used in conjunction with web frameworks like Express to ensure that requests made to the server are legitimate and not forged by malicious actors.
What are csrf's main functionalities?
Generate CSRF Token
This feature allows you to generate a CSRF token. First, you create a new instance of the csrf class, then generate a secret, and finally create a token using that secret.
const csrf = require('csrf');
const tokens = new csrf();
const secret = tokens.secretSync();
const token = tokens.create(secret);
console.log('CSRF Token:', token);
Validate CSRF Token
This feature allows you to validate a CSRF token. You generate a secret and a token, and then use the verify method to check if the token is valid.
const csrf = require('csrf');
const tokens = new csrf();
const secret = tokens.secretSync();
const token = tokens.create(secret);
const isValid = tokens.verify(secret, token);
console.log('Is the token valid?', isValid);
Other packages similar to csrf
csurf
The csurf package is another middleware for CSRF token creation and validation, specifically designed to work with Express.js. It provides similar functionality to csrf but is more tightly integrated with Express, making it easier to use in Express applications.
csrf-csrf
The csrf-csrf package is a lightweight alternative for CSRF protection. It offers similar functionalities to csrf but is designed to be simpler and more straightforward, making it a good choice for smaller projects or those that do not require the full feature set of csrf.
CSRF
Logic behind CSRF token creation and verification.
Read Understanding-CSRF for more information on CSRF.
Use this module to create custom CSRF middleware and what not.
Install
$ npm install csrf
API
var csrf = require('csrf')(options)
var secret = csrf.secretSync()
var token = csrf.create(secret)
var valid = csrf.verify(secret, token)
Options
secretLength: 18
- the byte length of the secret keysaltLength: 8
- the string length of the salttokenize: (secret, salt) => token
- a custom token creation function
csrf.secret([cb])
Asynchronously create a new secret
of length secretLength
.
If cb
is not defined, a promise is returned.
You don't have to use this.
csrf.secret().then(function (secret) {
})
csrf.secret(function (err, secret) {
})
var secret = csrf.secretSync()
Synchronous version of csrf.secret()
var token = csrf.create(secret)
Create a CSRF token based on a secret
.
This is the token you pass to clients.
var valid = csrf.verify(secret, token)
Check whether a CSRF token is valid based on a secret
.
If it's not valid, you should probably throw a 403
error.
License
MIT