CSRF tokens for koa
JavaScript
Latest commit 5b23a2d Jun 7, 2016 @stephenmathieson stephenmathieson Release 2.5.0
Failed to load latest commit information.
test add "disableQuery" option (#23) Jun 6, 2016
.gitignore csrf-tokens -> csrf Aug 22, 2014
.travis.yml travis: don't update npm May 4, 2015
HISTORY.md Release 2.5.0 Jun 6, 2016
LICENSE 2.0.0 Jun 8, 2014
README.md fix example Apr 27, 2016
example.js fix example Apr 27, 2016
index.js add "disableQuery" option (#23) Jun 6, 2016
package.json Release 2.5.0 Jun 6, 2016

README.md

Koa CSRF

NPM version Build status Test coverage Dependency Status License Downloads

CSRF tokens for koa.

Install

npm install koa-csrf

API

To install, do:

require('koa-csrf')(app, options)

Options

All options are passed to csrf-tokens.

this.csrf

Lazily creates a CSRF token. CSRF tokens change on every request. Returns null if session is invalid.

app.use(function* () {
  this.render({
    csrf: this.csrf
  })
})

this.assertCSRF([body])

Check the CSRF token of a request with an optional body. Will throw if the CSRF token does not exist or is not valid.

app.use(function* () {
  var body = yield parse(this) // co-body or something
  try {
    this.assertCSRF(body)
  } catch (err) {
    this.status = 403
    this.body = {
      message: 'This CSRF token is invalid!'
    }
    return
  }
})

Middleware

koa-csrf also provide a koa middleware, it is similar to connect-csrf. in most situation, you only need:

var koa = require('koa')
var csrf = require('koa-csrf')
var session = require('koa-session')

var app = koa()
app.keys = ['session secret']
session(app)
app.use(csrf())

app.use(function* () {
  if (this.method === 'GET') {
    this.body = this.csrf
  } else if (this.method === 'POST') {
    this.status = 204
  }
})