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 theDELETE /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: BearerHTTP 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
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 theAuthorization header with the Bearer schema.
http
*(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
8. Implementing Authorization (RBAC)
Now that we know the user is authenticated, we must implement Authorization (AuthZ) using Role-Based Access Control.
javascript
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
userIdandrole.
12. Exercises
- 1. Explain the chronological difference between Authentication (AuthN) and Authorization (AuthZ) in an API request pipeline.
13. Coding Challenges
-
Challenge: Look at the
authenticateTokenmiddleware. 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 theAuthorization: Bearer header, and we constructed sequential middleware guards in Express to elegantly intercept, verify, and enforce access control on protected routes.