Node.js Course
Node.js
/
Intermediate

JWT Authentication

Definition

JSON Web Token. A compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature structure.

Explain Like I'm New

A JWT is a digital VIP wristband. When you log in, the server checks your password. If it's correct, it generates a JWT string containing your User ID and cryptographically signs it. It gives you the wristband. Now, every time you want to view a private page, you show the wristband. The server mathematically verifies the signature. If it's legit, it lets you in without ever having to check your password or the database again!

Real World Example

Stateless authentication in React/Node apps. The Node server issues a JWT. The React app saves it in `localStorage` or an `httpOnly` cookie. The React app attaches it to the `Authorization: Bearer <token>` header on every single `fetch()` request.

Common Use Cases

  • •Stateless REST APIs
  • •Single Sign-On (SSO)
  • •Microservice authentication

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What are the three parts of a JWT?

intermediate

  • Is the payload of a JWT encrypted? Can anyone read it?

advanced

  • How do you invalidate or destroy a JWT before it expires?

Flash Cards

Question

What are the three parts?

Click to reveal answer
Answer

Header, Payload, and Signature. Separated by dots (xxxxx.yyyyy.zzzzz).

Question

Is the payload encrypted?

Click to reveal answer
Answer

NO! The payload is simply base64 encoded. Anyone who finds your JWT can paste it into jwt.io and read everything inside it. Never put passwords or secrets in the payload. The JWT is SIGNED (so it can't be tampered with), but it is NOT encrypted.

Question

How do you invalidate it?

Click to reveal answer
Answer

You inherently cannot. Because JWTs are stateless, the server doesn't keep a list of them. Once issued, a JWT is valid until its expiration date. To revoke them early, you must build a 'Token Blacklist' in your database, which defeats the entire 'stateless' benefit of JWTs.