CSRF tokens for Koa >= 2.x (next). For Koa < 2.x (next) see the 2.x branch.
For koa@>=2.x (next):
npm install --save [email protected]
For koa@<2.x:
npm install --save [email protected]
- 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';
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();
- 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>
- Existing methods from 1.x package added to 3.x
- Existing tests from 1.x package added to 3.x