Lesson 26 of 30

JWT Authentication

Chapter 26

JWT Authentication

Learn how JSON Web Tokens can be used for stateless authentication.

Theory

JWT stands for JSON Web Token. A JWT can be issued after successful authentication and then sent by the client when accessing protected resources. A JWT commonly contains: • Header • Payload • Signature The server verifies the token before allowing access to protected resources. Sensitive information should not be placed in a JWT payload simply because it is encoded; JWT payload contents are generally readable by whoever possesses the token.

Example

Node.js Example
const jwt = require("jsonwebtoken");

const token = jwt.sign(
  { userId: 123 },
  "example-secret",
  { expiresIn: "1h" }
);

console.log(token);

Output

A signed JWT is generated for the user.

Practice

Build a simple Express login endpoint that creates a JWT after successful authentication.

Interview Questions

1.

What is JWT?

2.

What are the parts of a JWT?

3.

Why should sensitive information not be stored directly in a JWT payload?

Quick Quiz

Which option best matches this chapter?

A.JSON Web Token
B.Java Web Transfer
C.JavaScript Web Table
D.JSON Worker Tool

Answer: JSON Web Token