Skip to content

coogleyao/csrf

 
 

Repository files navigation

Koa CSRF

NPM version Build status Test coverage Dependency Status License Downloads

CSRF tokens for Koa >= 2.x (next). For Koa < 2.x (next) see the 2.x branch.

Install

For koa@>=2.x (next):

npm install --save koa-csrf@3.x

For koa@<2.x:

npm install --save koa-csrf@2.x

Usage

  1. Add middleware in Koa app (default options are shown):
import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import session from 'koa-generic-session';
import convert from 'koa-convert';
import CSRF from 'koa-csrf';

const app = new Koa();

// set the session keys
app.keys = [ 'a', 'b' ];

// add session support
app.use(convert(session()));

// add body parsing
app.use(bodyParser());

// add the CSRF middleware
app.use(new CSRF({
  invalidSessionSecretMessage: 'Invalid session secret',
  invalidSessionSecretStatusCode: 403,
  invalidTokenMessage: 'Invalid CSRF token',
  invalidTokenStatusCode: 403,
  excludedMethods: [ 'GET', 'HEAD', 'OPTIONS' ],
  disableQuery: false
}));

// your middleware here (e.g. parse a form submit)
app.use((ctx, next) => {

  if (![ 'GET', 'POST' ].includes(ctx.method))
    return next();

  if (ctx.method === 'GET') {
    ctx.body = ctx.csrf;
    return;
  }

  ctx.body = 'OK';

});

app.listen();
  1. Add the CSRF token in your template forms:

Jade Template:

form(action='/register', method='POST')
  input(type='hidden', name='_csrf', value=csrf)
  input(type='email', name='email', placeholder='Email')
  input(type='password', name='password', placeholder='Password')
  button(type='submit') Register

EJS Template:

<form action="/register" method="POST">
  <input type="hidden" name="_csrf" value="<%= csrf %>" />
  <input type="email" name="email" placeholder="Email" />
  <input type="password" name="password" placeholder="Password" />
  <button type="submit">Register</button>
</form>

Open Source Contributor Requests

  • Existing methods from 1.x package added to 3.x
  • Existing tests from 1.x package added to 3.x

About

CSRF tokens for koa

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%