Use JSON Web Token with Koa

JSON Web Token (JWT) is used to issue a secure authentication token once the user successfully logs in. In Koa we use the koa-jwt middleware to manage these tokens.

npm install koa-jwt --save

Import the package from your code.

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

We can use the middleware to guard access to protected URLs. The following will try to decrypt the token sent with the request using the secret key 'pa$$word'. If that does not succeed the processing pipeline will be terminated and the subsequent middlewares will not run. We use the unless escape hatch so that this token validation is skipped for paths starting with "/public".

app.use(jwt({ secret: 'pa$$word' })
    .unless({ path: [/^\/public/] }));

Add the jwt middleware before any routes for it to have any meaningful effect.

A new token is issued using jwt.sign(). You can store identifying information like user ID, name etc. as a payload in the token.

api.get('/public/login', function *(){
    var user = {
      userId: "bibhas",
      name: "Bibhas B"
    }

    this.body = {
      token: jwt.sign(user, "pa$$word")
    }
});

A client is responsible for saving the token and sending it back with every request using the Authorization header. In the example below ABCXYZ is a token issued by the server:

curl -H "Authorization: Bearer ABCXYZ" localhost:8080/protected-stuff

The middleware saves the payload decrypted from the token as the state.user property of the context. So we can easily access that as follows:

api.get('/protected-stuff', function *(){
    var userId = this.state.user.userId //"bibhas"
    var fullName = this.state.user.name //"Bibhas B"
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s