DEV Community

Cover image for JSON Web Tokens Simplified
Matt Eland
Matt Eland Subscriber

Posted on • Originally published at newdevsguide.com

JSON Web Tokens Simplified

JSON Web Tokens are a standard way of managing authenticated access to web services. But JSON Web Tokens, also called JWTs (pronounced “Jot”) can be intimidating.

JSON Web Tokens are strings that are:

  • Provided by a server on authentication
  • Included in subsequent requests as a header on the request
  • Used to identify the requestor without having to re-authenticate on every request
  • Contain a few key pieces of information such as the user’s ID or role
  • Cryptographically signed so the server knows they were signed using a secret key
  • Not valid before a certain date and time
  • Not valid after a certain date and time

In this article we’ll explore what JWTs are by comparing them to something that most of us already understand: hotel keycards.

Hotel Keycards applied to JWT Authentication

JWT Authentication

I often travel to speak at programming conferences. The conference organizers will typically pay for my hotel and all I need to do is show up at the hotel, show them my ID, take care of a few details, and then head to my room.

When I provide my driver’s license, name, and conference name, I am authenticating myself to the receptionist.

Authentication is the process of proving I am who I say I am by providing relevant credentials or documentation.

In web applications authentication may occur in a variety of ways including:

  • Username and password
  • Signing in with external credentials such as a Google or Microsoft account
  • Biometric means such as a face ID or fingerprint reader
  • An authentication app, text code, or E-Mail code as a form of multi-factor authentication (MFA)
  • A hardware-based security key connected to a machine

Regardless of what way the user authenticates themself, the server returns a JSON Web Token (JWT). This JWT has been signed by the server and includes information on the user’s identity as well as the time range the JWT is valid for.

In the same way, when I check in to a hotel, they give me a keycard. This keycard includes information on my guest, my room, and the date range that the token is valid for.

JWT Authorization

Once the front desk gives me a keycard (the JWT in our metaphor), I now have freedom to move about the hotel and use that keycard to get into any room I am authorized to enter.

Authorization is the process of validating that a known user has access to what they are attempting to use. For example, an authenticated user at a bank is authorized to view their own balance, but not a stranger’s.

In our hotel analogy, I can use my keycard to get into my hotel room, the fitness center, business center, and pool area.

When I use my keycard to enter these places, I do not need to provide my driver’s license and reservation information because I am already authenticated. Instead, I present the keycard and the server recognizes it as a valid keycard for a current guest.

The server must then authorize me and make sure I have access to the resource I am trying to access.

As a guest I should be authorized to enter my room, my floor, the fitness center, and the pool. However, I should not be authorized to enter a random hotel room, the penthouse suite, or potentially other floors. Even though the hotel knows who I am through the keycard, they still don’t want me to have complete freedom throughout the hotel as this would compromise other guests’ safety and privacy.

The key thing here is that you authorize once and then use the token for subsequent requests.

In REST this token is typically included in the Authorization header with a value of Bearer {JWT} where {JWT} is the full JSON Web Token string.

Anonymous Access

While we’re talking about authentication and authorization, let’s talk briefly about anonymous access.

This past week I travelled 5 hours to a conference and arrived at the hotel at 10 PM. There was little to eat on the road and the restaurant closed at 11, so I wanted to eat before I checked in and unloaded my car.

Even though I had not yet authenticated or gotten a keycard, I still had access to the restaurant, bathrooms, and other public areas of the hotel.

The hotel had no idea who I was (aside from when I paid for my food) and they didn’t care since I was in a public area. To them I was anonymous.

Anonymous access in web development refers to portions of an application or API that can be accessed without having to provide authentication or a valid JSON Web Token.

When you don’t want or need to require authorized access, you can mark resources on your server as allowing anonymous access. The exact syntax for this differs based on what web framework you are running, but it can be as simple as adding an [AllowAnonymous] attribute in ASP .NET for example.

Many new developers want to make sure every endpoint requires authentication, and this is often a good idea, but some portions of your site you may want people to interact with before they log in.

Common pages that should allow anonymous access can include:

  • Your product’s home page
  • The log in page or endpoint
  • Recover password page
  • Sign up / register page
  • About / contact us pages

A critical thing to keep in mind is that pages or endpoints that allow you to log in or register should always allow anonymous access. Failure to do so prevents people from being able to get a JWT to use for future authentication.


Let’s apply that to our hotel metaphor.

Imagine I pulled up to the hotel. It’s 10 PM and raining and I’ve been driving for 5 hours. I walk up to the doors to the lobby and find that they’re locked and require me to use a keycard. Inside, the receptionist smiles helpfully and points to the keycard slot, then goes back to her work.

In this scenario, the lobby no longer allows anonymous access. Therefore, I need a keycard to get into the lobby. However I can’t get a keycard until I enter the lobby!

This hotel clearly wouldn’t get much repeat business.

Not Valid Before / Expires At

Let’s talk about a final part of JWT access: date ranges.

JSON Web Tokens often include iat, nbf, and exp properties. These three are various times:

  • iat is short for Issued At and represents the date and time the JWT was generated
  • nbf is short for Not Valid Before and indicates the earliest date and time the JWT will be valid
  • exp is short for Expires and indicates the latest date and time the JWT will be valid

You can use not valid before and expires to issue a JWT that is only valid for a specific time range.

Typically, JSON Web Tokens are valid immediately and expire at some point in the future. However, you could potentially generate a JWT that activates a week from today if your business scenarios require this.

When I check into a hotel I’m given a keycard that is valid for the duration of my stay. If I’m staying for 2 days, that keycard will typically be active immediately and will expire at checkout time (or shortly thereafter).

Let’s say a guest keeps their keycard after their stay and returns weeks later. They still have the keycard the hotel issued, and it is still a keycard generated by the hotel. However, that keycard has expired and shouldn’t allow you access to any areas that required authentication including their old hotel room.

In the same way, exp and nbf on a JSON Web Token tell the server that an otherwise valid token should not be honored when the date and time are outside of the token’s date range.

Modifying JWTs

With that note on exp and nbf on JSON Web Tokens you may be wondering “What if someone modifies the token’s properties to look like they’re still valid?”

This is not an article on the structure of JSON Web Tokens or the cryptographic principles behind them. However, it’s important to briefly discuss how JSON Web Tokens are tamper resistant.

Since JSON Web Tokens are just encoded strings, you could use a tool like JWT.io to view the contents of any JWT and even try to modify the contents of that token.

However, JWTs are signed using a cryptographic hash by the server that lets the server know if the contents of the JWT no longer match the hash signature.

Since the cryptographic hash is generated by the server using a secret known only to the server, the server will be able to detect that the contents of the JWT no longer match the signature of the JWT and the JWT must not have been signed by the server. As a result, the JWT is not considered valid and cannot be used to authenticate the user.

Final Thoughts on JWT Authentication

It feels like JSON Web Token authentication is everywhere nowadays, and it can be really intimidating the first time you see it.

However, I am consistently impressed with how helpful students find the metaphor of a JWT as a hotel keycard is.

Let’s close with a final summary and comparison:

When a user logs in to a site, they provide some form of credentials that the server authenticates. Once they are authenticated, the server returns a JWT that they can then use in subsequent requests. In the same way, a hotel grants a guest a keycard once the guest proves they are who they say they are.

Once you have a JWT you can include that JWT in subsequent REST requests as an Authorization header without having to provide credentials again. This is similar to how guests at a hotel can use their keycard to enter their room without having to prove their identity all over again.

Just because you have a JWT doesn’t mean you have access to all parts of an application. For example, just because I use a social media application and am authenticated there doesn’t mean I should be able to delete other user’s content. In the same way, a hotel keycard gives you access to your room and not all rooms.

Finally, JSON Web Tokens typically expire and are no longer valid after a certain date or time. Once that happens users will need to log in again and get a new JWT. In the same way, a hotel keycard doesn’t grant lifetime access to a hotel room (at least not at the conferences I speak at!) and that keycard is only effective during the guest’s stay.


I hope this metaphor helps you as much as it helps my students. I’d love to hear other comparisons you might spot or other metaphors you might use for this or other parts of tech.

Top comments (3)

Collapse
 
raviklog profile image
raviklog

Nice starter article on JWT

Collapse
 
bigbott profile image
bigbott

My 5 cents.
I like the idea of JWT authentication.
From my experience as a Java programmer JWT authentication significantly faster than traditional Java approach i.e. servlet session and easier scallable.
JWT standard is overcomplicated.

Conclusion: instead of using standard JWT library and assymetric signing/verifying, use custom JWT with symmetric (AES) encryption/decryption.
By custom JWT I mean something like this:
{"userId" : 12345, "role": "user"}
You encrypt it and use as access token - store in cookie with short time expiration.
For refresh token just use:
12345
You encrypt it and store in long time expiration cookie.
KISS.

Collapse
 
integerman profile image
Matt Eland

That'd be a great article to write. This article is about helping people grasp the basics of JWTs and their usage.