JSON Web Tokens
Last week, I went over what Middleware and what different types of middleware may be used for. I left off on a note about authorization and included a code snippet. Let’s take a look at that code snippet now:
As I’ve mentioned, this code snippet checks for a token to authorize a user’s action on the client. What is this token exactly, though? Well, you’ve probably guessed JSON Web Tokens, and you’d be right. Let’s now get into what exactly JSON Web Tokens are and why they’re so important for authorization.
Authentication vs. Authorization
I want to start off by first saying it’s important to distinguish between authentication and authorization. Let’s say a user is trying to log into a website. They type in their username and password, but the password is incorrect and they’re denied access to the account, or the password is correct and they have been granted access to the account. This is authentication. The server authenticates the information passed into it to grant the user in the client access to the account they’re trying to log into. Authorization is basically a set of permissions that the user now has. For example, a Facebook user may be able to delete their own posts, but they cannot delete another person’s posts. That user does not have the authorization to do so, unlike a Facebook admin who would be able to delete that post.
JWT
So what does JWT do? Basically, JWT is a token that the server checks to see is valid and then grants you access to certain resources from the server. Let’s take a look at this chart from JWT’s official documentation:
Let’s break this down into 3 steps:
- The client sends a request to the authorization server for a token.
- The server then grants authorization by sending a token back to the client.
- The client then uses that token to access routes that require a valid token.
So what does the JWT actually look like? Here’s a screenshot from the debugger on jwt.io:
The left panel is what the token actually looks like. The right panels are how that token is created. Let’s now break down the panels:
Header: The actual algorithm used to encode and decode the token.
Payload: The data stored within the actual token (yes, the token is more than just a “security code”).
Verify Signature: This checks if the token has been tampered with in between time of creation and the request. Also contains a secret “key” that determines HOW the data is encoded (this is the line where “ThisIsYourSecretCode!” is).
I 100% recommend going to https://jwt.io/ to play around with it yourself.