GithubHelp home page GithubHelp logo

koa-jwt's Introduction

koa-jwt

Koa middleware that validates JSON Web Tokens and sets ctx.state.user (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.

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.

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.

Normally you provide a single shared secret in opts.secret, but another alternative is to have an earlier middleware set ctx.state.secret, typically per request. If this property exists, it will be used instead of the one in opts.secret.

Example

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

var app = koa();

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

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

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

// Protected middleware
app.use(function *(){
  if (this.url.match(/^\/api/)) {
    this.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 = 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 *(next){
  if (this.url.match(/^\/public/)) {
    this.body = 'unprotected\n';
  } else {
    yield next;
  }
});

// Protected middleware
app.use(function *(){
  if (this.url.match(/^\/api/)) {
    this.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.

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' }));

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

Related Modules

Note that koa-jwt exports the sign, verify and decode functions from the above module as a convenience.

Tests

$ npm install
$ npm test

Author

Stian Grytøyr

Credits

This code is largely based on express-jwt.

Contributors

License

The MIT License

koa-jwt's People

Contributors

stiang avatar getuliojr avatar cesarandreu avatar jackong avatar michaelwestphal avatar soygul avatar foxandxss avatar sdd avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.