Koa middleware that validates JSON Web Tokens and sets
(by default) if a valid token is provided.
This module lets you authenticate HTTP requests using JSON Web Tokens in your Koa (node.js) applications.
See this article for a good introduction.
$ npm install koa-jwt-comm
The JWT authentication middleware authenticates callers using a JWT
token. If the token is valid,
ctx.user (by default) will be set
with the JSON object decoded to be used by later middleware for
authorization and access control.
var koa = ;var jwt = ;var app = ;// Custom 401 handling if you don't want to expose koa-jwt errors to usersapp;// Unprotected middlewareapp;// Middleware below this line is only reached if JWT token is validapp;// Protected middlewareapp;app;
Alternatively, you can add the
passthrough option to always yield next,
even if no valid Authorization header was found:
This lets downstream middleware make decisions based on whether
ctx.user is set.
If you prefer to use another ctx key for the decoded data, just pass in
key, like so:
This makes the decoded data available as
You can specify audience and/or issuer as well:
If the JWT has an expiration (
exp), it will be checked.
This module also support tokens signed with public/private key pairs. Instead of a secret, you can specify a Buffer with the public key:
var publicKey = fs;app;
- jsonwebtoken — JSON Web Token signing and verification
Note that koa-jwt exports the
decode functions from the above module as a convenience.
$ npm install $ npm test
This code is largely based on express-jwt.