• Stars
    star
    1,333
  • Rank 35,259 (Top 0.7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Koa middleware for validating JSON Web Tokens

koa-jwt

Koa middleware for validating JSON Web Tokens.

node version npm download npm stats test status coverage license

Table of Contents

Introduction

This module lets you authenticate HTTP requests using JSON Web Tokens in your Koa (node.js) applications.

See this article for a good introduction.

  • If you are using koa version 2+, and you have a version of node < 7.6, install koa-jwt@2.
  • koa-jwt version 3+ on the master branch uses async / await and hence requires node >= 7.6.
  • If you are using koa version 1, you need to install koa-jwt@1 from npm. This is the code on the koa-v1 branch.

Install

npm install koa-jwt

Usage

The JWT authentication middleware authenticates callers using a JWT token. If the token is valid, ctx.state.user (by default) will be set with the JSON object decoded to be used by later middleware for authorization and access control.

Retrieving the token

The token is normally provided in a HTTP header (Authorization), but it can also be provided in a cookie by setting the opts.cookie option to the name of the cookie that contains the token. Custom token retrieval can also be done through the opts.getToken option. The provided function should match the following interface:

/**
 * Your custom token resolver
 * @this The ctx object passed to the middleware
 *
 * @param  {Object}      opts The middleware's options
 * @return {String|null}      The resolved token or null if not found
 */

opts, the middleware's options:

  • getToken
  • secret
  • key
  • isRevoked
  • passthrough
  • cookie
  • audience
  • issuer
  • debug

The resolution order for the token is the following. The first non-empty token resolved will be the one that is verified.

  • opts.getToken function.
  • check the cookies (if opts.cookie is set).
  • check the Authorization header for a bearer token.

Passing the secret

One can provide a single secret, or array of secrets in opts.secret. An alternative is to have an earlier middleware set ctx.state.secret, typically per request. If this property exists, it will be used instead of opts.secret.

Checking if the token is revoked

You can provide a async function to jwt for it check the token is revoked. Only you set the function in opts.isRevoked. The provided function should match the following interface:

/**
 * Your custom isRevoked resolver
 *
 * @param  {object}   ctx            The ctx object passed to the middleware
 * @param  {object}   decodedToken   Content of the token
 * @param  {object}   token          token The token
 * @return {Promise}                 If the token is not revoked, the promise must resolve with false, otherwise (the promise resolve with true or error) the token is revoked
 */

Example

var Koa = require('koa');
var jwt = require('koa-jwt');

var app = new Koa();

// Custom 401 handling if you don't want to expose koa-jwt errors to users
app.use(function(ctx, next){
  return next().catch((err) => {
    if (401 == err.status) {
      ctx.status = 401;
      ctx.body = 'Protected resource, use Authorization header to get access\n';
    } else {
      throw err;
    }
  });
});

// Unprotected middleware
app.use(function(ctx, next){
  if (ctx.url.match(/^\/public/)) {
    ctx.body = 'unprotected\n';
  } else {
    return next();
  }
});

// Middleware below this line is only reached if JWT token is valid
app.use(jwt({ secret: 'shared-secret' }));

// Protected middleware
app.use(function(ctx){
  if (ctx.url.match(/^\/api/)) {
    ctx.body = 'protected\n';
  }
});

app.listen(3000);

Alternatively you can conditionally run the jwt middleware under certain conditions:

var Koa = require('koa');
var jwt = require('koa-jwt');

var app = new Koa();

// Middleware below this line is only reached if JWT token is valid
// unless the URL starts with '/public'
app.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/public/] }));

// Unprotected middleware
app.use(function(ctx, next){
  if (ctx.url.match(/^\/public/)) {
    ctx.body = 'unprotected\n';
  } else {
    return next();
  }
});

// Protected middleware
app.use(function(ctx){
  if (ctx.url.match(/^\/api/)) {
    ctx.body = 'protected\n';
  }
});

app.listen(3000);

For more information on unless exceptions, check koa-unless.

You can also add the passthrough option to always yield next, even if no valid Authorization header was found:

app.use(jwt({ secret: 'shared-secret', passthrough: true }));

This lets downstream middleware make decisions based on whether ctx.state.user is set. You can still handle errors using ctx.state.jwtOriginalError.

If you prefer to use another ctx key for the decoded data, just pass in key, like so:

app.use(jwt({ secret: 'shared-secret', key: 'jwtdata' }));

This makes the decoded data available as ctx.state.jwtdata.

You can specify audience and/or issuer as well:

app.use(jwt({ secret:   'shared-secret',
              audience: 'http://myapi/protected',
              issuer:   'http://issuer' }));

You can specify an array of secrets.

The token will be considered valid if it validates successfully against any of the supplied secrets. This allows for rolling shared secrets, for example:

app.use(jwt({ secret: ['old-shared-secret', 'new-shared-secret'] }));

Token Verification Exceptions

If the JWT has an expiration (exp), it will be checked.

All error codes for token verification can be found at: https://github.com/auth0/node-jsonwebtoken#errors--codes.

Notifying a client of error codes (e.g token expiration) can be achieved by sending the err.originalError.message error code to the client. If passthrough is enabled use ctx.state.jwtOriginalError.

// Custom 401 handling (first middleware)
app.use(function (ctx, next) {
  return next().catch((err) => {
    if (err.status === 401) {
      ctx.status = 401;
      ctx.body = {
        error: err.originalError ? err.originalError.message : err.message
      };
    } else {
      throw err;
    }
  });
});

If the tokenKey option is present, and a valid token is found, the original raw token is made available to subsequent middleware as ctx.state[opts.tokenKey].

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.readFileSync('/path/to/public.pub');
app.use(jwt({ secret: publicKey }));

If the secret option is a function, this function is called for each JWT received in order to determine which secret is used to verify the JWT.

The signature of this function should be (header, payload) => [Promise(secret)], where header is the token header and payload is the token payload. For instance to support JWKS token header should contain alg and kid: algorithm and key id fields respectively.

This option can be used to support JWKS (JSON Web Key Set) providers by using node-jwks-rsa. For example:

const { koaJwtSecret } = require('jwks-rsa');

app.use(jwt({ 
  secret: koaJwtSecret({
    jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json',
    cache: true,
    cacheMaxEntries: 5,
    cacheMaxAge: ms('10h') 
  }),
  audience: 'http://myapi/protected',
  issuer: 'http://issuer' 
}));

Related Modules

  • jsonwebtoken β€” JSON Web Token signing and verification.

Note that koa-jwt no longer exports the sign, verify and decode functions from jsonwebtoken in the koa-v2 branch.

Tests

npm install
npm test

Authors/Maintainers

Credits

The initial code was largely based on express-jwt.

Contributors

License

MIT

More Repositories

1

koa

Expressive middleware for node.js using ES2017 async functions
JavaScript
34,326
star
2

examples

Example Koa apps
JavaScript
4,471
star
3

bodyparser

Koa body parsing middleware
TypeScript
1,273
star
4

static

Static file server middleware
JavaScript
1,124
star
5

compose

Middleware composition utility
JavaScript
986
star
6

koa-body

koa body parser middleware
TypeScript
923
star
7

session

Simple session middleware for koa
JavaScript
902
star
8

router

Router middleware for Koa. Maintained by @forwardemail and @ladjs.
JavaScript
790
star
9

cors

Cross-Origin Resource Sharing(CORS) for koa
JavaScript
723
star
10

kick-off-koa

[MAINTAINERS WANTED] An intro to koa via a set of self-guided workshops
JavaScript
693
star
11

logger

Development style logging middleware
JavaScript
561
star
12

mount

Mount other Koa applications or middleware to a given pathname
JavaScript
549
star
13

ratelimit

Rate limiter middleware
JavaScript
466
star
14

joi-router

Configurable, input and output validated routing for koa
JavaScript
450
star
15

route

Simple route middleware
JavaScript
442
star
16

workshop

Koa Training Workshop
JavaScript
436
star
17

compress

Compress middleware for koa
JavaScript
432
star
18

koa.io

[MAINTAINERS WANTED] Realtime web framework combine koa and socket.io.
JavaScript
427
star
19

send

Transfer static files
TypeScript
420
star
20

generic-session

koa session store with memory, redis or others.
JavaScript
414
star
21

koa-redis

Redis storage for Koa session middleware/cache with Sentinel and Cluster support
JavaScript
352
star
22

koala

[SEEKING MAINTAINER] An HTTP/2 and ES6 Module-ready Koa Suite
JavaScript
320
star
23

static-cache

[MAINTAINERS WANTED] Static cache for koa
JavaScript
293
star
24

csrf

CSRF tokens for koa
JavaScript
265
star
25

react-view

A Koa view engine which renders React components on server
JavaScript
256
star
26

convert

Convert koa generator-based middleware to promise-based middleware
JavaScript
254
star
27

ejs

a koa view render middleware, support all feature of ejs
JavaScript
248
star
28

json

pretty-printed JSON response middleware
JavaScript
197
star
29

todo

a todo example write with koa and react
JavaScript
165
star
30

koa-hbs

Handlebars templates for Koa.js
JavaScript
159
star
31

cash

HTTP response caching for Koa. Supports Redis, in-memory store, and more!
JavaScript
154
star
32

onerror

an error handler for koa, hack ctx.onerror
JavaScript
139
star
33

basic-auth

blanket basic auth middleware
JavaScript
138
star
34

userauth

koa user auth middleware
JavaScript
137
star
35

multer

Middleware for handling `multipart/form-data` for koa, based on Express's multer.
JavaScript
137
star
36

response-time

X-Response-Time middleware
JavaScript
124
star
37

trie-router

Trie-routing for Koa
JavaScript
122
star
38

koa-roles

koa version of Connect-Roles
JavaScript
117
star
39

etag

ETag support for Koa responses
JavaScript
112
star
40

bunyan-logger

Koa middleware for bunyan request logging
JavaScript
108
star
41

favicon

Koa middleware for serving a favicon
JavaScript
104
star
42

error

Error response middleware (text, json, html)
JavaScript
103
star
43

rewrite

URL rewriting middleware
JavaScript
100
star
44

json-filter

Middleware allowing the client to filter the response to only what they need, reducing the amount of traffic over the wire.
JavaScript
92
star
45

json-error

Error handler for pure-JSON apps
JavaScript
89
star
46

qs

qs for koa, and use querystring more safely.
JavaScript
85
star
47

bigpipe-example

[DEPRECATED] BigPipe using koa and component
JavaScript
83
star
48

common

[DEPRECATED] USE INDIVIDUAL MODULES
JavaScript
77
star
49

locales

koa locales, i18n solution for koa
JavaScript
67
star
50

koa-lusca

koa version of lusca. Application security for koa.
JavaScript
65
star
51

cluster

Koa clustering and error handling utility
JavaScript
64
star
52

parameter

parameter validate middleware for koa, powered by parameter
JavaScript
62
star
53

conditional-get

Conditional GET middleware for koa
JavaScript
59
star
54

trace

generic tracing for koa
JavaScript
53
star
55

koa-range

[MAINTAINERS WANTED] range request implementation for koa, see http://tools.ietf.org/html/rfc7233
JavaScript
47
star
56

sendfile

basic file-sending utility for koa
JavaScript
45
star
57

koajs.com

The koajs.com website
HTML
42
star
58

mock

Simple web page mock middleware
JavaScript
40
star
59

body-parsers

collection of koa body parsers
JavaScript
37
star
60

koa-markdown

Auto convert markdown to html for koa. Inspired by connect-markdown
JavaScript
37
star
61

koa-gzip

[Deprecated] please use koa-compress instead
JavaScript
36
star
62

file-server

file serving middleware for koa
JavaScript
36
star
63

bundle

Generic asset pipeline with caching, etags, minification, gzipping and sourcemaps.
JavaScript
36
star
64

resourcer

A simple resource directory mounter for koa.
JavaScript
34
star
65

path-match

koa route middleware
JavaScript
33
star
66

html-minifier

minify HTML responses like some crazy guy
JavaScript
31
star
67

webcam-mjpeg-stream

[DEPRECATED] Stream JPEG snapshots from your Mac
JavaScript
28
star
68

timer

time your middleware
JavaScript
26
star
69

statsd

Statsd middleware
JavaScript
24
star
70

redis-session-sets

Koa Redis sessions with field-referencing cross sets
JavaScript
20
star
71

accesslog

Middleware for common log format access logs
JavaScript
19
star
72

is-json

check if a koa body should be interpreted as JSON
JavaScript
17
star
73

charset

use iconv-lite to encode the body and set charset to content-type
JavaScript
16
star
74

koa-safe-jsonp

Safe jsonp plusins for koa.
JavaScript
16
star
75

trace-influxdb

InfluxDB tracing for koa-trace
JavaScript
15
star
76

stateless-csrf

CSRF without sessions.
JavaScript
15
star
77

atomic-session

DEPRECATED
JavaScript
15
star
78

cross-cookies

Easily set cookies across subdomains
JavaScript
13
star
79

koa-github

simple github auth middleware for koa
JavaScript
13
star
80

s3-cache

Koa middleware to cache and serve from S3
JavaScript
11
star
81

eslint-config-koa

Koa's ESLint config, based on Standard
JavaScript
11
star
82

ctx-cache-control

Augment Koa with ctx.cacheControl(maxAge)
JavaScript
9
star
83

snapshot

take snapshot when request, cache by request path.
JavaScript
9
star
84

compressor

[DEPRECATED] Compress middleware for koa that always compresses
JavaScript
9
star
85

koa-fresh

DEPRECATED
JavaScript
8
star
86

cdn

[DEPRECATED] middleware for a koa-based CDN
JavaScript
7
star
87

koa-rt

koa rt with microtime
JavaScript
6
star
88

override-method

method override utility for koa
JavaScript
6
star
89

ctx-basic-auth

Augments Koa with ctx.basicAuth
JavaScript
5
star
90

resourcer-docs

[MAINTAINERS WANTED] Simple app that generates documentation for routes mounted using koa-resourcer.
JavaScript
5
star
91

middleware-hook

low-level hooks for your middleware
JavaScript
5
star
92

path

[DEPRECATED] path-matching middleware for koa
JavaScript
4
star
93

observable-redis-session

[DEPRECATED] Observable, atomic sessions for Koa using Redis
JavaScript
2
star
94

help

koa(1) executable for instant help
2
star
95

discussions

KoaJS Discussions
1
star