JSON Web Tokens (Again!) and Koa.js


Posted on

A few weeks ago, I wrote about using JSON Web Tokens (JWT) as an alternative method of authentication using Go. The post itself contains a basic explanation about JWT and some links for content. In this post, I want to cover pretty much the same things using Koa, a new framework for Node.js.

Koa is mostly a middleware framework which uses generators (only available under the Harmony flag) to control the flow of requests. The reason I mention that it’s a middleware framework is because it doesn’t come with most of the things you would expect a framework to provide, such as routing, body parsers, etc. However, when it comes to middleware, Koa is baller.

Artist-2296722-qttb

To The Code!

First, install the following packages:

This tutorial will be using RSA keys instead of simple strings, so you’ll have a better sense of what you could use in production. Generating your keys is as simple as running the following commands:

Now that we have all that we need, lets get some application code done:

Let’s go step by step. Initially, we just set up Koa normally and then we read our previously created public and private keys, which we’ll use to sign and verify the tokens.

Notice that the very first middleware is simply used to catch the errors that JWT might have in order to obfuscate the original errors. Followed by that, there’s a public endpoint where users go to obtain their tokens. Koa’s middleware gets executed in the order they are added to the pipeline, so everything that gets added after the introduction of the JWT middleware will require a valid signed token.

Let’s test this out!

Hope this tutorial was useful and entertaining! If you have any questions, doubts or concerns feel free to ping me! @elbuo8


Puerto Rican and hackNY '13 fellow. Always looking to hack/experiment something new. You can follow me @elbuo8

Yamil Asusta on Twitter
Have thoughts on this post?
Chat with us about it on Twitter and Google+