Skip to main content
REST API Design Tutorial
CHAPTER 10 Beginner

Authentication and Authorization in APIs

Updated: May 14, 2026
40 min read

# CHAPTER 10

Authentication and Authorization in APIs

1. Introduction

A beautifully structured, perfectly validated API is dangerous if anyone on the internet can access the DELETE /api/users endpoint. Securing an API requires two distinct phases: determining *who* is making the request (Authentication) and determining *what* they are allowed to do (Authorization). Because REST APIs are strictly stateless, we cannot rely on traditional browser cookies. In this chapter, we will explore how REST APIs handle identity management using JSON Web Tokens (JWTs), API Keys, and Role-Based Access Control (RBAC).

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Clearly define the difference between Authentication (AuthN) and Authorization (AuthZ).
  • Understand how stateless APIs verify identity without utilizing server RAM sessions.
  • Explain the role of JSON Web Tokens (JWT) in API security.
  • Transmit tokens via the Authorization: Bearer HTTP header.
  • Implement middleware to protect API routes and enforce user roles.

3. Beginner-Friendly Explanation

Imagine a high-security office building.
  • Authentication (AuthN): You walk up to the front door. The security guard asks for your driver's license. They verify the face matches the ID. You have proven *who* you are. The guard prints you a temporary ID Badge.
  • Authorization (AuthZ): You walk to the server room door. You swipe your ID Badge. The system checks the badge to see if you are a "Janitor" or an "IT Admin". If you are a Janitor, the light flashes red, and the door stays locked. It verifies *what* you are allowed to do.

In REST APIs, Authentication generates the JWT (The ID Badge), and Authorization checks the roles embedded inside that JWT.

4. The Stateless Problem

If you log into a traditional PHP website, the server remembers you by saving a Session ID in its RAM. As we learned in Chapter 2, REST APIs are strictly Stateless. The server forgets you the second the request ends. Therefore, to access a protected route, the Client must send its "ID Badge" with *every single request*.

5. JSON Web Tokens (JWT)

The industry standard "ID Badge" for REST APIs is the JWT. When a user logs in (POST /api/login), the API verifies the password, generates a cryptographically signed Token containing the user's ID and Role, and returns it to the Client.
json
123456
// The JWT Payload
{
  "userId": 42,
  "role": "admin",
  "exp": 1700000000 
}

6. Transmitting the Token (The Request)

The Client (React app or Mobile app) must save this token and attach it to future requests. The standard convention is to use the Authorization header with the Bearer schema.
http
123
GET /api/dashboard HTTP/1.1
Host: api.mywebsite.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsIn...

*(The term "Bearer" literally means "Give access to the bearer of this token".)*

7. Implementing Protection Middleware

To protect an endpoint, we write a Middleware function. This function intercepts the request, reads the Header, verifies the mathematical signature of the Token, and decides if the request can proceed.

Node.js/Express Example:

javascript
1234567891011121314151617181920212223
const jwt = require('jsonwebtoken');

// The Middleware Guard
function authenticateToken(req, res, next) {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Extract the token string

    if (!token) return res.status(401).json({ error: "Access Denied. No token provided." });

    // Mathematically verify the signature
    jwt.verify(token, process.env.SECRET_KEY, (err, decodedUser) => {
        if (err) return res.status(403).json({ error: "Invalid or expired token." });
        
        // Success! Attach the user payload to the request object
        req.user = decodedUser; 
        next(); // Proceed to the final route logic
    });
}

// Protecting the Route
app.get('/api/dashboard', authenticateToken, (req, res) => {
    res.json({ message: `Welcome User ID: ${req.user.userId}` });
});

8. Implementing Authorization (RBAC)

Now that we know the user is authenticated, we must implement Authorization (AuthZ) using Role-Based Access Control.
javascript
1234567891011121314
// Another Middleware Guard for Roles
function requireAdmin(req, res, next) {
    // We rely on req.user which was populated by authenticateToken
    if (req.user.role !== 'admin') {
        return res.status(403).json({ error: "Forbidden: Admin privileges required." });
    }
    next();
}

// Chaining Middlewares: Must be logged in AND must be an admin
app.delete('/api/users/:id', authenticateToken, requireAdmin, (req, res) => {
    // Delete logic...
    res.status(204).send();
});

9. Machine-to-Machine Authentication (API Keys)

If your API is designed to be accessed by automated scripts rather than human users via a frontend, you do not use JWTs. You use API Keys. An API key is a long, static string (e.g., sklivexyz123) provided to the developer. The script attaches this key to the X-API-Key header. The server looks up the key in the database to authenticate the script. (See the Backend Security tutorial for deep implementation of API Keys).

10. Best Practices

  • Short-Lived Access Tokens: Because stateless JWTs cannot easily be revoked (destroyed) from a central database if stolen, they must have very short lifespans (e.g., 15 minutes). You pair them with a long-lived, securely stored "Refresh Token" to keep the user logged in seamlessly without compromising security.

11. Common Mistakes

  • Putting Passwords in JWTs: Beginners often put the user's password hash or sensitive PII (Personally Identifiable Information) inside the JWT payload. JWT payloads are NOT encrypted; they are only Base64 encoded. Anyone who intercepts the token can decode and read the JSON payload. Only include meaningless identifiers like userId and role.

12. Exercises

  1. 1. Explain the chronological difference between Authentication (AuthN) and Authorization (AuthZ) in an API request pipeline.

13. Coding Challenges

  • Challenge: Look at the authenticateToken middleware. What specific HTTP Status Code is returned when the user fails to provide a token? What code is returned when the token is provided, but the mathematical signature verification fails?

14. MCQs with Answers

Question 1

In a stateless REST API architecture, how does the frontend client consistently prove its identity to the backend server on every request?

Question 2

If an API Request successfully passes the Authentication middleware (verifying the JWT), but fails the Authorization middleware (because the user is not an Admin), which HTTP Status Code should be returned?

15. Interview Questions

  • Q: Walk me through the implementation of JWT Authentication in a decoupled REST API. How is the token generated, where is it stored by the client, how is it transmitted, and how does the server verify it without looking up a database session?
  • Q: Explain Role-Based Access Control (RBAC). How do you architect Express.js middleware to enforce specific roles on specific endpoint routes?

16. FAQs

Q: What is OAuth 2.0? A: OAuth 2.0 is an industry-standard framework for *Delegated Authorization*. It allows a user to grant a third-party application (like your API) access to their data on another service (like Google or Facebook) without giving you their Google password. When users click "Log in with Google," that is OAuth 2.0 powering the complex token exchange under the hood.

17. Summary

In Chapter 10, we solved the challenge of securing stateless APIs. We established the two distinct phases of security: Authentication (verifying identity) and Authorization (verifying permissions). We explored the industry-standard mechanism of JSON Web Tokens (JWT), understanding how servers pack user roles into a signed payload. We learned how clients transmit these tokens via the Authorization: Bearer header, and we constructed sequential middleware guards in Express to elegantly intercept, verify, and enforce access control on protected routes.

18. Next Chapter Recommendation

Identity verification is critical, but APIs face external threats as well. Proceed to Chapter 11: API Security Best Practices.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·