Understanding How Authentication Works in APIs

Understanding How Authentication Works in APIs

Last updated: 3/7/2025

1 hour
Medium

Understanding How Authentication Works in APIs

🌍 Introduction

In the previous lesson, we learned that authentication verifies who a user is.
But how does authentication actually work in a REST API?

In this lesson, you'll learn:

  • How authentication works step-by-step in APIs.
  • The difference between stateful (session-based) and stateless (token-based) authentication.
  • How JSON Web Tokens (JWT) are used for authentication.

πŸ“Œ 1. How Authentication Works in an API (Step-by-Step)

When a user logs in to an API, the process follows these steps:

βœ… Step 1: User Sends Login Credentials

  • The user enters their email and password and sends a POST request to the /login endpoint.
POST /login Content-Type: application/json
{ "email": "user@example.com", "password": "securepassword" }

βœ… Step 2: API Verifies Credentials

  • The API hashes the password and checks if it matches the stored hash in the database.
  • If the credentials are correct, the API generates a session or token.

βœ… Step 3: API Responds with a Token

If authentication is successful, the server sends a token back to the client.

Response:

{ "token": "eyJhbGciOiJIUzI1NiIsInR..." }
  • This token proves that the user is authenticated.
  • The client must include this token in future requests.

βœ… Step 4: User Makes Requests with the Token

For each request to a protected route, the client sends the token in the Authorization header.

Example: Fetching user data

GET /profile Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR...

The API validates the token before processing the request.


βœ… Step 5: API Verifies the Token and Responds

  • If the token is valid, the API returns the requested data.
  • If the token is missing or invalid, the API responds with 401 Unauthorized.

Example Error Response (Invalid Token):

{ "error": "Unauthorized", "message": "Invalid or expired token" }

πŸ“Œ 2. Stateful vs. Stateless Authentication

There are two main ways to manage authentication in APIs:

MethodDescriptionProsCons
Stateful (Session-based)Stores session data on the serverMore secureRequires server memory
Stateless (Token-based)Uses tokens without storing sessionsScalableToken can be stolen

βœ… RESTful APIs prefer stateless authentication using JWT (JSON Web Tokens).


πŸ“Œ 3. What is a JSON Web Token (JWT)?

JWT (JSON Web Token) is a compact and secure way to transmit authentication data.

βœ… Example JWT Structure:

A JWT looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJ1c2VySWQiOjEsInJvbGUiOiJ1c2VyIiwiaWF0IjoxNjkyNDQ0MjAwfQ
.4H9G0l8MP96GmDlCsc6Kzx-ROfA

JWTs have three parts:

  1. Header β†’ Contains metadata (e.g., token type, signing algorithm)
  2. Payload β†’ Stores user data (e.g., user ID, role)
  3. Signature β†’ Ensures the token hasn't been tampered with

βœ… Example Decoded JWT:

{ "userId": 1, "role": "user", "iat": 1692444200 }
  • The userId identifies the user.
  • The role can be used for authorization (Admin/User).
  • The iat (issued at) timestamp indicates when the token was created.

πŸ“Œ 4. Why Use JWT for Authentication?

βœ… Stateless β†’ No need to store sessions on the server.
βœ… Secure β†’ Tokens can be signed to prevent tampering.
βœ… Fast β†’ No database lookup needed for every request.

However, JWTs should be used carefully:

  • Tokens should expire to prevent long-term misuse.
  • Use HTTPS to protect tokens from being stolen.

🎯 Summary

  • Authentication in APIs involves verifying user credentials and issuing a token.
  • Clients must send the token in the Authorization header for protected requests.
  • JWT (JSON Web Token) is commonly used for stateless authentication.
  • Stateless authentication is preferred in REST APIs for scalability.

βœ… Next Lesson: Implementing Basic Authentication in a REST API

In the next lesson, we’ll implement user authentication using JWTs in an Express.js API. πŸš€