All Articles

JSON Web Token (JWT) Authentication

JWT

JSON Web Tokens (JWT), as the name implies, is a form of token-based authentication. Its mechanisms and format are defined by an open standard that anyone can read (though you probably need a few advanced degrees to understand the nitty gritty details).

How it works

At a high level JWT works pretty much the same as other tokens. The key difference is in how the token is generated.

A JWT’s header will contain the token type (JWT) and its signing algorithm:

{ "typ": "JWT", "alg": "RS256" }

Common algorithms used for JWTs are:

  • RS256 (RSA via SHA256)
  • HS256 (HMAC via SHA256)

We won’t cover how algorithms work in this series (because it’s out of scope and because I’m certainly not a cryptographer!), but the Front to Back course will cover how we might determine the right algorithm to use in certain scenarios.

The JWT payload contains data called claims. For example, the claims might tell us:

  • What is the user’s ID? (token claims we can access this user’s data)
  • What permissions are allowed? (token claims the right to access for these privileges)
  • When was the token issued? (token claims it was generated at X time)
  • How long should authentication last? (token claims access for X amount of time)

Arbitrary data can also be sent in the payload, though it’s generally good practice to keep the payload small to decrease latency.

Why you should (or shouldn’t) use it

The pros and cons of any token-based auth apply to JWTs. Because all JWTs are cryptographically signed, they are great for security. The slower the signing algorithm, the more secure the token.

However, there are a few common footguns that can undermine a JWT’s security. A user can send an unsigned JWT with the None signature, and if the recipient accepts the token without validating, a malicious actor can easily gain access.

Additionally, it’s important that the signature requires a secure secret. Many developer demos will use a simplistic secret value that is easier to guess. Think of your secrets like your own passwords: make them long and obscure, and you’ll be secure.