Understanding How Authentication Works in APIs
Understanding How Authentication Works in APIs
Last updated: 3/7/2025
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:
Method | Description | Pros | Cons |
---|---|---|---|
Stateful (Session-based) | Stores session data on the server | More secure | Requires server memory |
Stateless (Token-based) | Uses tokens without storing sessions | Scalable | Token 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:
- Header β Contains metadata (e.g., token type, signing algorithm)
- Payload β Stores user data (e.g., user ID, role)
- 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. π