Package Exports
- koa-csrf
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (koa-csrf) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Koa CSRF
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.xFor koa@<2.x:
npm install --save koa-csrf@2.xUsage
- 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') RegisterEJS 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