JSON Web Tokens (JWT) with Restify
This is a very simple example of signing and verifying JSON Web Tokens using Restify. If you’d like more information on either subject, check out the following links:
First, we’ll need to install a few dependencies
$ npm i --save restify restify-jwt-community jsonwebtoken
restifywill act as our api server (developed by Netflix engineer Yunong J Xiao)
retify-jwt-communityis a middleware we'll use to validate json web tokens
jsonwebtokenis a library we'll use to create and sign json web tokens
As a sidenote: we could just as easily accomplish this without the use of extra middleware. However,
restify-jwt-community (forked from
auth0/express-jwt), provides us with a simple interface and drops a
req.user property for quick reference. Second, we’ll start with a very basic restify server:
Nothing too out of the ordinary here. We include a local
config.json module and for now, this can just be a simple object. The important thing is to define a secret which can be used throughout your application. Whether this comes from a config file or environment variable is up to you 😊
secret above will be used to sign and validate json web tokens throughout our app, so you'll want to be sure to make it unique. However, without any endpoints, this server is a bit useless in its current state.
Moving right along
Let’s assume we have some simple login system that returns very generic information about the supplied credentials:
Obviously, we’re mocking a response above but, any real implementation would work here — like the piece commented out. As such, we can add the following to our
server.js (save for further input validation).
This allows us to (insecurely) POST to an /auth route with some credentials to get our mocked response — probably less than surprising at this point.
Sign, Deliver and Validate JWT
Now let’s secure any and all of our endpoints (except for /auth). Then we’ll need to update our /auth handler to instead reply with a JWT:
Our reply now gives us a JSON Web Token and details about when it was issued at (iat) and the time it expires (exp). At this point, let’s hit our /auth endpoint again and see the altered response.
In our example, the token will automatically expire in 15 minutes — consumers will then need to either re-authenticate our look at refreshing the token.
Now we can start using our /user endpoint. By default, it will respond with a
401 Unauthorized if no
Authorization header is passed in the request. The Auth header value should be formatted as
Bearer [token] or
Jwt [token] according to the tests.
If you’d like to view the full example: