# Authentication at the Gateway — API Gateway and Service Mesh

Source: https://www.geekswithgeeks.com/en/api-gateway-service-mesh/s-auth-edge

> Validate API keys or tokens once at the edge and pass identity to services.

## Reject early, cheaply

Authenticating at the gateway means unauthenticated requests never reach your services, saving their capacity and shrinking the attack surface. The gateway can check **API keys** (a lookup), validate **JWTs** (signature, issuer, audience, expiry using the identity provider's public keys), or call an **external authorisation service**. Return **`401`** for missing or invalid credentials and **`403`** when the identity is known but not allowed. Pass the verified identity downstream (a header or a re-signed token) and let services still enforce their own **object-level authorisation**, because the gateway cannot know which order belongs to which user. Defence in depth means a compromised gateway should not equal a compromised system.

## Check once, at the door

The gateway authenticates callers, limits abuse and terminates TLS so services stay simple.

![Three controls: identify, limit, encrypt.](assets/figures/api-gateway-service-mesh/section-3-map.svg) — Figure 3.1 — Identify, limit and encrypt.

## An API-key check (config)

A `map` turns the `X-API-Key` header into a yes/no flag and the location returns `401` when it is not valid. Real gateways load keys from a store, never hard-code them.

```nginx
map $http_x_api_key $api_ok { default 0; "demo-key-123" 1; }

location /orders/ {
  if ($api_ok = 0) { return 401 '{"error":"missing or invalid API key"}\n'; }
  proxy_pass http://orders_weighted/;
}
```

## No key, wrong key, right key, run

I ran this against a real nginx 1.27 gateway in Docker, with small Node.js services as upstreams (full setup in the case study). Without a key and with a wrong key the gateway answers `401` itself (the first line shows the JSON body); with the right key the request is proxied and returns `200`.

```bash
GET /orders/x
GET /orders/x  X-API-Key: wrong
GET /orders/x  X-API-Key: demo-key-123
```

Output:

```
401 {"error":"missing or invalid API key"}
401 200
```

## Use JWT validation for users, keys for apps

API keys identify an application; they say nothing about which person is calling. For user-facing APIs prefer OAuth 2.0 / OIDC tokens validated at the edge.

**Quiz:** Which status should the gateway return for a request with no credentials?

- [ ] 204 No Content
- [ ] 403 Forbidden
- [x] 401 Unauthorized
- [ ] 302 Found

*Answer:* 401 Unauthorized. 401 means the caller is not authenticated; 403 means authenticated but not allowed.
