JWT, access token, token, OAuth token.. what does it all mean??

Properly known as “JSON Web Tokens”, JWTs are a fairly new player in the authentication space. Being the cool new thing, everyone is hip to start using them. But are you doing it securely? In this article we’ll discuss user authentication best practices in Node.js using JWTs, while showing you how to use the nJwt library for creating and verifying JWTs in your Node.js application.

What is a JSON Web Token (JWT)?

In a nutshell, a JWT is an object that can tell you things about a user and what they’re allowed to do. JWTs are meant to be issued by a trusted authority and given to a user. Typically this means your server is creating the JWT and sending it to your user’s web browser or mobile device for safe keeping.

JWTs can be digitally signed with a secret key. Doing so allows you to assert that a token was issued by your server and was not maliciously modified.

When the token is signed, it is “stateless”: this means you don’t need any extra information, other than the secret key, to verify that the information in the token is “true”. This great feature allows you to remove that pesky session table in your database.

When Should I Use Them?

JWTs are typically used to replace session identifiers. For example: if you’re using a session system which stores an opaque ID on the client in a cookie while also maintaining session in a database for hat ID. With JWTs you can replace both the session data and the opaque ID.

You’ll still use a cookie to store the access token, but you need to make sure you secure your JWT cookies. For more information on that topic I’ll refer you to my other post, Build Secure User Interfaces Using JSON Web Tokens (JWTs).

With the token stored in a secure cookie, the user’s client will supply the token on every subsequent request to your server. This allows the server to authenticate the request, without having to ask for credentials a second time (until the token expires, that is).

How to Create a JWT

There are a few things you’ll need in order to create a JWT for a user, we’ll walk through each of these steps in detail:

  1. Generate the secret signing key
  2. Authenticate the user
  3. Prepare the claims
  4. Generate the token
  5. Send the token to the client

1. Generate the Secret Signing Key

To be secure, we want to sign our tokens with a secret signing key. This key should be kept confidential and only accessible to your server. It should be highly random and not guessable. In our example, we’ll use the node-uuid library to create a random key for us:

2. Authenticate the User

Before we can make claims about the user, we need to know who the user is. So the user needs to make an initial authentication request, typically by logging into your system by presenting a username and password in a form. It could also mean that they’ve presented an API key and secret to your API service, using something like the Authorization: Basic scheme.

In either situation, your server should verity the user’s credentials. After you’ve done this and obtained the user data from your system, you want to create a JWT which will “remember” the information about the user. We’ll put this information into the claims of the token.

3. Prepare The Claims

Now that we have the user data, we want to build the “claims” of the JWT. That will look like this:

Let’s discuss each of these fields. Technically speaking, you can create a JWT without any claims. But these three fields are the most common:

  • sub – This is the “subject” of the token, the person whom it identifies. For this field you should use the opaque user ID from your user management system. Don’t use personally identifiable information, like an email address.

  • iss – This is the “issuer” field, and it lets other parties know who created this token. This could be the URL of your website, or something more specific if your website has multiple applications with different user databases.

  • permissions – Sometimes you’ll see this as scope if the JWT is being used as an OAuth Bearer Token. This is simply a comma-seperated list of things that the user has access to do.

4. Generate the Token

Now that we have the claims and the signing key, we can create our JWT object:

This will be our internal representation of the token, before we send it to the user. Let’s take a look at what’s inside of it:

You will see an object structure which describes the header and the claims body of the token:

You’ll see the claims that you specified earlier, and many other properties. These are the secure defaults that our library is setting for you, let’s visit each one in detail:

  • alg – This declares how we’ve signed our token, in this case using the Hmac algorithm with a strength of 256 bits. If you want more security, you can bump this up to HS512

  • exp – This is the time that the token will expire, as a unix timestamp offset in seconds. By default our library sets this to 1 hour in the future. If you need to change this value, call jwt.setExpiration() and pass a Date object that represents the desired expiration time.

  • iat – This is the time that the token was created, as a unix timestamp offset in seconds.

  • jti – This is simply a random value, that is created for every JWT. We provide this in case you want to create a database of tokens that were issued. You may do this if you want to implement a token blacklist for tokens that you know have been compromised (i.e. a user tells you their account has been hacked into).

5. Send the Token to the Client

Now that we have the JWT object, we can “compact” it to get the actual token, which will be a Base64 URL-Safe string that can be passed down to the client.

Simply call compact, and then take a look at the result:

What you see will look like this:

This is the compact JWT, it’s a three-part string (separated by periods). It contains the encoded header, body, and signature.

How you send the token to the client will depend on the type of application you are working with. The most common use case is a login form on a traditional website. In that situation you will store the cookie in an HttpOnly cookie, so you can simply set the cookie on the POST response.

For example, if you’re using the cookies library for Express:

Once the client has the token, it can use it for authentication. For example, if you’re building a single-page-app, the app will be making XHR requests of your server. When it does so, it will supply the cookie for authentication.

How to Verify JWTs

When a client has a token it will use it to authenticate the user. The token can be sent to your server in a cookie or an HTTP header, such as the Authorization: Bearer header.

For example, if it comes in as a cookie and you’re using the cookies library with your Express app, you could pull the token from the cookie like this:

Regardless of how the token comes in, it will be that same compacted string that you sent to the client. To verify the string, you simply need to pass it to the verify method in the library, along with the secret key that was used to sign the token:

If the token is valid, you can log it to the console and see the same information that you put into it!

If the token is invalid, the verify method will throw an error which describes the problem:

If you don’t want to throw errors you can use the verify function asynchronously:

JWTs Made Easy!

That’s it! Creating and verifying JWTs is incredibly simple, especially with the API that nJwt gives you. No go forth and JWT all the services!

But remember: do it securely. While our nJwt library does all the security for the JWT, you also need to ensure that you application is using cookies securely. Please see my other article for an in-depth walkthrough of the security concerns:

Build Secure User Interfaces Using JSON Web Tokens (JWTs)

Happy verifying!