Security
🎯 Introduction
A signed-in user queries their orders through a BFF. If the BFF has already verified their identity, why must orders check again? When orders calls inventory, how does inventory know the request really came from orders?
Using these two scenarios, this article answers three questions: which user the request represents, which service actually sent it, and whether the operation is authorized. Earlier courses covered JWT issuance and HTTPS configuration; here we focus on their use in microservices.
🧱 User Identity, Service Identity, and Business Authorization
Suppose user A requests order o-100 through the BFF:
| Question | Meaning | Check in this example |
|---|---|---|
| User identity | Which user does this operation represent? | Is it really user A? |
| Service identity | Who is calling orders? | Is it an allowed BFF? |
| Business authorization | Which data may this user access? | Does o-100 belong to user A? |
These checks do not substitute for one another:
- Verifying the BFF does not make every user ID it supplies trustworthy.
- Verifying that user A is signed in does not authorize access to someone else's orders.
- Verifying an internal service does not grant access to every internal endpoint.
🔑 Propagating User Identity to Orders
We can continue using access tokens from the JWT course. This design is straightforward: the BFF validates the user token, and orders independently validates a user token intended for orders.
courseComponents.mermaid.loading
The flow has four steps:
- After login, the browser receives an access token and submits it to the BFF with order requests.
- The BFF validates the token and checks whether the request may enter the order flow.
- Over a protected internal connection, the BFF passes a token orders can validate.
- Orders validates the token itself, then checks order ownership using the verified identity.
An easily missed detail is that not every valid JWT is valid for orders. Orders must check the signature, issuer (iss), audience (aud), expiration, and permissions required by the endpoint. If aud permits only the BFF, that token cannot simply be treated as an order-service token. A trusted identity system must exchange it for one intended for orders.
Do not trust X-User-Id from the browser or ordinary request headers. The user ID must come from successfully verified identity information, rather than an arbitrary caller-supplied string.
🛡 Authorizing Orders to Call Inventory
A user token answers which user is represented. When orders requests a reservation, inventory must also verify which service is calling.
This course explains the flow with short-lived signed service tokens, without covering mTLS or service mesh configuration.
courseComponents.mermaid.loading
For example, orders obtains a short-lived token from a trusted identity system with these claims:
{
"iss": "internal-identity",
"sub": "orders-service",
"aud": "inventory-service",
"scope": "inventory:reserve",
"exp": 1794900000
}
exp is an expiration timestamp. Calculate a short lifetime dynamically from the current time when issuing real tokens; do not copy this example value.
These fields illustrate the payload. JSON alone cannot prevent forgery; the digital signature must also be verified. On receiving the request, inventory:
- Verifies the signature, issuer, audience, and expiration.
- Confirms that the caller is
orders-service. - Checks the
inventory:reservepermission. - Checks the reservation parameters and business rules.
Even a valid token does not justify skipping step three. Payments should not gain unrestricted reservation and release permissions merely by running on the internal network.
X-Service-Name: orders-service cannot replace a service token: any program capable of sending requests could supply it. Internal network access controls reduce risk but are not authentication.⚠️ Why Authenticated Users Can Still Access Unauthorized Data
Suppose orders exposes:
GET /orders/o-100
After signing in, user A replaces the order ID with one belonging to user B. If orders only validates the JWT, it may return B's order to A.
Therefore, authentication must be followed by an ownership check. Using the Express application structure from earlier lessons, the core authorization logic is:
app.get('/orders/:orderId', authenticateUser, async (req, res) => {
const order = await findOrderById(req.params.orderId);
if (!order) {
return res.sendStatus(404);
}
if (order.userId !== req.user.id) {
return res.sendStatus(403);
}
return res.json(order);
});
authenticateUser and findOrderById are the existing project's authentication middleware and order query function, not Node.js built-ins. This assumes authenticateUser has validated the token as described above and populated req.user.id with a trusted user ID; it must not read an unverified header directly. The example checks ordinary users' ownership only. Special access, such as administrator permissions, requires additional explicit rules. A real project may return 404 consistently to avoid revealing whether an order exists.
This endpoint checks two separate things: whether the user really is A, and whether A may view this order. If only the BFF may call it, verify the calling service separately before the business route runs.
🔒 Least Privilege and Service Credentials
Beyond identity, restrict what each service may do:
| Caller | Allowed operation | Permission it should not have |
|---|---|---|
| BFF | Access order endpoints for authenticated users | Bypass ownership checks |
| Order service | Request reservation or release under business rules | Modify the inventory database directly |
| Payment service | Report outcomes through protected APIs or events | Read every user's full order information arbitrarily |
This is the principle of least privilege: grant only permissions required for the task.
Keep signing keys, database passwords, and broker credentials separate for each service, and out of Git, logs, and business events. Production systems should distribute them securely through secret management and support key rotation. Services should not indefinitely share one all-powerful credential.
❓ Knowledge Check
Q1: Why must orders verify the user if the BFF already did?
Orders still needs trustworthy identity information and must authorize access to the specific order. This article uses independent validation of an appropriate token to make that boundary explicit.
Q2: Can user and service identity share one token?
Avoid casually combining them. A user token identifies whom the request represents; a service token identifies the calling program. Their audiences, purposes, and permissions may differ, so validate them according to an explicit trust design.
Q3: Can internal-only endpoints skip service authentication?
Do not rely solely on the internal network. Network isolation provides one layer, but inventory must still identify callers and check permissions if an internal program is misused.
🧪 Exercise
Design the checks for POST /orders/:orderId/cancel, answering:
- How do you identify the user represented by the request?
- If only the BFF may call it, how do you verify service identity?
- How do you verify order ownership?
- Why must cancellation eligibility still be checked after identity and permissions pass?
Acceptance criteria: Changing an order ID cannot cancel someone else's order; impersonating the BFF cannot grant internal permissions; an order that is paid and ineligible for direct cancellation cannot be canceled solely because authentication passed.
🎉 Congratulations on completing this article! You can now distinguish user identity, service identity, and business authorization, and establish clear security boundaries between orders and inventory.
Fault Tolerance and Reliability
Use order-to-inventory calls to learn timeouts, bounded retries, circuit breakers, isolation, and graceful degradation, preventing downstream failures from spreading.
Observability
Locate failures across order service requests using request correlation IDs, structured logs, metrics, and distributed tracing.
