DEV Community

Shehzaib
Shehzaib

Posted on

JWT Authentication Explained: Access vs Refresh Tokens

What is JWT?
JWT stands for JSON Web Token. Let's break this down simply. Imagine you need to send a message or information from one person (or computer) to another in a safe way, especially over the internet. JWT is like a special envelope for that information. It's made in a format called JSON (which is just a simple way to organize data, like a list of key-value pairs, e.g., "name": "John", "age": 26). This envelope is "compact" (small and efficient) and "URL-safe" (it can be put into web addresses without causing problems). The key part is that it's secure; it can be signed or encrypted so that only the right people can read or trust it.
JWTs are often used in web apps (like websites or mobile apps) for two main things:

Authentication: Proving who you are (like logging in).
Information exchange: Sharing details securely between different parts of a system.

Now let's talk about how JWTs are used for authentication, specifically with two types of tokens: access tokens and refresh tokens. These help keep your login session (the time you're signed in) safe and smooth.

Access Tokens: The Short-Term Key
An access token is like a temporary pass or key that lets you enter protected areas of a website or app. Think of it as a ticket to a movie; it's given to you after you prove who you are, and it allows you to "access" (use) certain things on behalf of the user (you).

Short lifespan: It doesn't last long; maybe just a few minutes to a few hours. This is on purpose! If someone steals it, they can't use it forever, which makes it safer.

Stored in memory: It's kept in a temporary spot on your device (like in the app's short-term memory, not saved to a file or disk). This reduces risks because if your device is hacked, it's harder for thieves to find and steal it.

What it contains: Inside the token, there's info about you, like your user ID (who you are) and permissions (what you're allowed to do, e.g., view your profile but not delete others').
What happens when it expires: Once it's old and no longer valid, you can't use it anymore. Your app has to get a new one to keep going.

In simple terms, the access token is your "quick-entry pass" that's easy to use but expires fast to stay secure.

Refresh Tokens: The Long-Term Backup
A refresh token is like a master key that lets you get a new access token when the old one expires. It's not for directly accessing stuff; it's just for "refreshing" (renewing) your temporary pass.

Long lifespan: This one lasts much longer, maybe days or weeks. Because it's powerful (it can create new access tokens), it needs extra protection.

Stored securely: It's usually saved in something called an HttpOnly cookie. Let's explain that:

A cookie is a small piece of data that a website stores on your browser (the program you use to surf the web, like Chrome).
HttpOnly means this cookie can only be sent over HTTP (the way web pages communicate) and can't be touched by JavaScript. This protects it from attacks like XSS (Cross-Site Scripting), which is when bad guys inject harmful code into a website to steal your info.

Invalidation: If needed, the server (the main computer running the website) can make the refresh token invalid. This is useful for logging you out forcefully or revoking access (e.g., if your account is compromised).

In short, the refresh token is your "renewal card". It's hidden away safely and used only when you need a fresh access token.

How Access Tokens and Refresh Tokens Work Together

User Login:
You enter your credentials: That's your username (or email) and password.
The server checks if they're correct. If yes, it creates and sends back two things: an access token (your temporary pass) and a refresh token (your renewal card).

Application Load (When You Open the App or Website):
Your app or browser checks if there's a valid access token in its memory.
If there's no token or it's expired (too old), the app sends the refresh token to the server.
The server verifies the refresh token (makes sure it's real and not expired). If it's good, it sends a brand-new access token.

Accessing Resources (Using Protected Parts of the Site):

When you want to do something secure (like view your account details), your app attaches the access token to the request.
It does this in a special header called Authorization. The format is: Authorization: Bearer .

Header: Think of it as a label on the message your app sends to the server.
Bearer: This just means "the token is the proof. Let the bearer (holder) in."

The server checks the token: Is it valid? Not expired? From a real user? If yes, it lets you access the stuff.

Token Expiry and Refresh (When Things Expire):

If the access token expires while you're using the app, your requests will fail. The server might send back an "unauthorized" error (like "Hey, your pass is invalid!").
Your app notices this and sends the refresh token to the server.
Server checks it and, if valid, issues a new access token. Now you can continue without logging in again.

Logout:

If the refresh token is invalid (maybe it expired, or the server revoked it), you get logged out. You might need to enter your username and password again.
This is also how the system can force a logout, like if you click "Log Out" or if there's suspicious activity.

Why This System is Secure and User-Friendly

Security: Short-lived access tokens mean less time for hackers to misuse them. Refresh tokens are hidden from common attacks (like XSS). You can revoke tokens if something goes wrong.
Ease for Users: You don't have to log in every few minutes—the refresh token handles renewals automatically, keeping your session going smoothly.
Overall: This setup is common in modern web apps because it balances safety with convenience. No need to store passwords on your device, and it reduces risks from stolen data.

Top comments (0)