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

Use Angular 2 from an ExpressJS Application

Most Angular 2 starter projects use a development time web server. This will not work well if you are developing the application using Node and Express. An Angular 2 project works best when it is the document root of a web server. This requires a bit of careful planning.

In today’s post I will explore how to create a Express application that uses Angular 2. We will explore two separate approaches:

  • A single project hosting both Node and Angular 2 code.
  • Separate projects for Node and Angular 2 code.

We will use generators and official starter projects whenever possible. This will help you follow along this article and experiment quickly.

Continue reading