Logic behind CSRF token creation and verification.
Logic behind CSRF token creation and verification.
Read Understanding-CSRF for more information on CSRF. Use this module to create custom CSRF middleware.
Looking for a CSRF framework for your favorite framework that uses this module?
$ npm install csrf
This module includes a TypeScript declaration file to enable auto complete in compatible editors and type information for TypeScript projects.
var Tokens = require('csrf')
Create a new token generation/verification instance. The
optionsargument is optional and will just use all defaults if missing.
Tokens accepts these properties in the options object.
The length of the internal salt to use, in characters. Internally, the salt is a base 62 string. Defaults to
8characters.
The length of the secret to generate, in bytes. Note that the secret is passed around base-64 encoded and that this length refers to the underlying bytes, not the length of the base-64 string. Defaults to
18bytes.
Create a new CSRF token attached to the given
secret. The
secretis a string, typically generated from the
tokens.secret()or
tokens.secretSync()methods. This token is what you should add into HTML blocks and expect the user's browser to provide back.
var secret = tokens.secretSync() var token = tokens.create(secret)
Asynchronously create a new
secret, which is a string. The secret is to be kept on the server, typically stored in a server-side session for the user. The secret should be at least per user.
tokens.secret(function (err, secret) { if (err) throw err // do something with the secret })
Asynchronously create a new
secretand return a
Promise. Please see
tokens.secret(callback)documentation for full details.
Note: To use promises in Node.js prior to 0.12, promises must be "polyfilled" using
global.Promise = require('bluebird').
tokens.secret().then(function (secret) { // do something with the secret })
A synchronous version of
tokens.secret(callback). Please see
tokens.secret(callback)documentation for full details.
var secret = tokens.secretSync()
Check whether a CSRF token is valid for the given
secret, returning a Boolean.
if (!tokens.verify(secret, token)) { throw new Error('invalid token!') }