OAuth2 JWT middleware
Last updated 5 years ago by runk .
MIT · Original npm · Tarball · package.json
$ cnpm install jwt-middleware 
SYNC missed versions from official npm registry.


This middleware supports server-to-server interactions and not when you authorize on behalf of end user so that consent is not required. JWT (JsonWebToken) is a part of OAuth2 specification http://oauth.net/documentation/ and designed to simplify server-to-server flow.

Middleware setup

First of all we encourage you to develop secure services and to use in this particular case private/public RSA (RS256) keys for signing and verifying JWT signatures. So that server would have an access to client's public key and only client has access to his private key. Although middleware supports other algos such as "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "ES256", "ES384", and "ES512". Check node-jws for more details: https://github.com/brianloveswords/node-jws.

var JwtMiddleware = require('jwt-middleware')

var clientsKeys = {
  'alpha@adslot.com': '[public key in PEM format goes here]'

var auth = new JwtMiddleware({
  ttl: 3600, // access token life time
  store: {
    type: 'encrypted',
    secret: 'very long s3cr3t key'
  getKey: function(payload, cb) {
    // Third argument is optional and can be used to extend session object with server-side params
    cb(null, clientKeys[payload.client_id], {uid: 1});

app.post('/oauth/token', auth.token.bind(auth));
app.post('/method/name', auth.check.bind(auth), function(req, res, next) {
  // Prints consolidated object of JWT's payload and session obj
  console.log(req.session); // -> {uuid: 1, client_id: 'alpha@adslot.com'}
  res.send('Protected resource');


Middleware has two prebuilt stores, which keep registry of issued access tokens.

  • encrypted - uses 'cookie-style' way. Basically tokens are not stored anywhere, but they are cryptographically encrypted and contain meta information about session, expiry time etc.
  • momory - uses memory, so it would be error-prone if you're using nodejs cluster or running several children node processes (they do not share memory).

You can create you own custom store (redis/mysql/whatever). Please take a look at the code in lib/store dir for examples. Feel free to post a pull request if you crafted it, so other people can use!

Cilent flow

For the client, simplified OAuth2 flow consists of those steps:

  • Create a JWT, which includes a header, a claim set, and a signature. More information about creating JWT you can find in official spec: http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25.

  • Request an access token from the OAuth 2.0 Authorization Server (this middleware).

    POST /oauth/token HTTP/1.1
    Host: api.adslot.com
    Content-Type: application/x-www-form-urlencoded

    where assertion is a JWT generated by a client.

  • Handle the JSON response that the Authorization Server returns. If the response includes an access token, use the access token to call a API. (If the response does not include an access token, your JWT and token request might not be properly formed, or has invalid signature). More details can be found here: http://tools.ietf.org/html/rfc6750.

      "access_token": "wdg0icrQWbb-3FmzQ_oOqA2TR76Bu",
      "token_type": "Bearer",
      "expires_in": 1800
  • Call protected resource by either including access token as a query parameter:

    GET https://api.adslot.com/method/name?access_token=wdg0icrQWbb-3FmzQ_oOqA2TR76Bu

    or by using Authorization header:

    GET https://api.adslot.com/method/name HTTP/1.1
    Authorization: Bearer wdg0icrQWbb-3FmzQ_oOqA2TR76Bu
    Host: api.adslot.com
  • When the access token expires, client's application generates another JWT, signs it, and requests another access token.


PRs are highly welcome!

You can generate keys using this snippet:

openssl req -x509 -days 365 -newkey rsa:2048 -keyout private.pem -out public.pem -nodes

Developed by Adslot.com

Current Tags

  • 0.3.0                                ...           latest (5 years ago)

7 Versions

  • 0.3.0                                ...           5 years ago
  • 0.2.0                                ...           5 years ago
  • 0.1.2                                ...           6 years ago
  • 0.1.1                                ...           6 years ago
  • 0.1.0                                ...           6 years ago
  • 0.0.2                                ...           6 years ago
  • 0.0.1                                ...           6 years ago
Maintainers (1)
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 0
Dependencies (1)
Dev Dependencies (2)
Dependents (0)

Copyright 2014 - 2017 © taobao.org |