JSON Web Tokens (Again!) and Koa.js


August 22, 2014
Written by
SendGrid Team
Contributor
Opinions expressed by Twilio contributors are their own

JSON Web Tokens (Again!) and Koa.js

Previously, 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

Recommended For You



Most Popular


Send With Confidence

Partner with the email service trusted by developers and marketers for time-savings, scalability, and delivery expertise.