In Lecture 6, we learned that breaking a monolith into microservices improves scalability and deployment speed. However, this introduces a new problem for the client (e.g., a mobile app or web browser). If an e-commerce application has 50 different microservices, does the mobile app need to know 50 different IP addresses and URLs?
Furthermore, if every microservice requires the user to log in, how do we prevent the user from having to authenticate 50 times? The solution to this chaos is the API Gateway.
An API Gateway is an API management tool that sits between a client and a collection of backend services. It acts as a reverse proxy, accepting all application programming interface (API) calls, aggregating the various services required to fulfill them, and returning the appropriate result.
Instead of the client talking to the microservices directly, the client only talks to the API Gateway. The Gateway acts as the single entry point ("front door") for the entire system.
Figure 1: API Gateway Architecture separating public clients from private microservices.
Popular API Gateways include Kong, NGINX, Amazon API Gateway, and Apigee. They perform several critical functions beyond just routing traffic:
/api/users to the User Service and /api/billing to the Billing Service. It can also aggregate data from multiple services into a single response.When integrating systems over the internet, security is paramount. We must distinguish between two concepts:
Modern APIs heavily rely on the OAuth 2.0 framework for authorization and JSON Web Tokens (JWT) for stateless authentication.
In traditional web apps, the server remembers you using a "Session ID" stored in its memory. In a microservices architecture with hundreds of servers, this is impossible. Instead, we use Stateless Authentication via JWT.
When a user logs in successfully, the Auth Service issues a JWT. The client (mobile app) attaches this token to every subsequent API request. The API Gateway inspects the token, validates its cryptographic signature, and routes the request.
A JWT consists of three parts separated by dots (.): Header, Payload, and Signature. Because it is digitally signed, the API Gateway knows if a hacker tries to alter the payload.
Specifies the algorithm used for the signature.
{
"alg": "HS256",
"typ": "JWT"
}
Contains the user's data and token expiration time.
{
"sub": "1905551042",
"name": "I Wayan Sudarma",
"role": "STUDENT",
"exp": 1679000000
}
3. Signature: The Gateway uses a secret key to verify the token. If a hacker tries to change their "role": "STUDENT" to "role": "ADMIN", the signature will become invalid, and the API Gateway will immediately block the request with a 401 Unauthorized error.