Pular para o conteúdo

API Gateway

Entrada única para os serviços internos: autenticação, roteamento e proxy na mesma cadeia; o cliente nunca vê endereço interno.

passos
4
arquivos
5
testes
0
tecnologias
5

Cenário

O app chama contas e pagamentos via gateway com JWT; contas confia no x-subject escrito só pelo gateway, mesmo se o cliente forjar.

Planta

Sequência
6/6
GET /accounts/0001/balance (Bearer JWT)1valida JWT HS256, issuer e audience (401)2prefixo para upstream (404)3proxy com x-subject, sem o token4resposta5resposta6App do clienteGatewayServiço de contas
6

6 passos — reproduza para seguir o fluxo

Como funciona

4passos

Entrada única para os serviços internos com autenticação, roteamento e proxy na mesma cadeia

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    Valida o JWT (algoritmo, issuer, audience, expiração)

  2. 2

    Primeiro segmento do caminho escolhe o upstream; desconhecido → 404

  3. 3

    Remove authorization e x-subject do cliente e escreve o seu

  4. 4

    Proxy com timeout

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Autenticação e log uniformes

  • Topologia interna oculta

Custos

  • Ponto único de falha

  • Um hop a mais

Código

pattern/api/gateway

5 arquivos

./

  • .env.exampleinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar só Bun

  1. bun install# dependências
  2. bun run demo# roda o cenário

Saída: 200 vindo de accounts, com subject app-mobile (o x-subject forjado é descartado) e tokenForwarded false.

Requisitos
Bun

Código

src/demo.ts

// Demo: the app calls one public entry; the gateway authenticates the JWT, routes by prefix and forwards the subject.
import { Elysia } from "elysia";
import { SignJWT, jwtVerify } from "jose";

// The upstreams only the gateway knows; clients never see these addresses.
const UPSTREAMS: Record<string, string> = { accounts: Bun.env.GATEWAY_ACCOUNTS_URL ?? "http://localhost:3001", payments: Bun.env.GATEWAY_PAYMENTS_URL ?? "http://localhost:3002" };
const UPSTREAM_TIMEOUT_MS = 1_000;
// HS256 key the identity provider signs client tokens with. The default exists only so the demo runs as is.
const secret = new TextEncoder().encode(Bun.env.GATEWAY_JWT_SECRET ?? "demo-only-secret-change-me-0123456789");

// Internal services trust x-subject because only the gateway can reach them; they echo what they received.
const upstreams = Object.entries(UPSTREAMS).map(([service, url]) =>
  new Elysia().all("/*", ({ request }) => ({ service, path: new URL(request.url).pathname, subject: request.headers.get("x-subject"), tokenForwarded: request.headers.has("authorization") })).listen(new URL(url).port),
);

async function subjectAuthenticate(authorization: string | null): Promise<string | undefined> {
  if (!authorization?.startsWith("Bearer ")) return undefined;
  const verified = await jwtVerify(authorization.slice(7), secret, { algorithms: ["HS256"], issuer: "bank-idp", audience: "bank-gateway" }).catch(() => undefined);
  return verified ? String(verified.payload.sub) : undefined;
}

// The single public entry: authenticate, route by the first path segment, strip the token, assert the subject.
const gateway = new Elysia().all("/*", async ({ request }) => {
  const subject = await subjectAuthenticate(request.headers.get("authorization"));
  if (!subject) return Response.json({ error: "unauthenticated" }, { status: 401 });
  const url = new URL(request.url);
  const base = UPSTREAMS[url.pathname.split("/")[1] ?? ""];
  if (!base) return Response.json({ error: "route-not-found" }, { status: 404 });
  const headers = new Headers(request.headers);
  // A client must never assert the subject itself: only the gateway writes x-subject.
  for (const name of ["authorization", "host", "x-subject"]) headers.delete(name);
  headers.set("x-subject", subject);
  return fetch(`${base}${url.pathname}${url.search}`, { method: request.method, headers, signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) });
}, { parse: "none" });

const token = await new SignJWT({}).setProtectedHeader({ alg: "HS256" }).setSubject("app-mobile").setIssuer("bank-idp").setAudience("bank-gateway").setExpirationTime("5m").sign(secret);
const response = await gateway.handle(new Request("http://gateway/accounts/0001/balance", { headers: { authorization: `Bearer ${token}`, "x-subject": "admin" } }));
console.log(`  [APP] GET /accounts/0001/balance → ${response.status} ${await response.text()}`);
await Promise.all(upstreams.map((upstream) => upstream.stop(true)));

Nível

introdutório

0/13

Linhas de TypeScript
34
Tipo
A — código puro

Domínio financeiro

  • Conta corrente

Padrões do catálogo que implementa

  • API Gateway
  • Gateway Routing
  • Gateway Offloading

Variáveis de ambiente

GATEWAY_ACCOUNTS_URL
http://localhost:3001
Accounts upstream, reachable only by the gateway.
GATEWAY_PAYMENTS_URL
http://localhost:3002
Payments upstream, reachable only by the gateway.
GATEWAY_JWT_SECRET
demo-only-secret-change-me-0123456789
HS256 key the identity provider signs client tokens with.

Trilhapasso 6 de 6

Do monólito aos serviços

  1. 1Arquitetura Monolítica
  2. 2Monólito Modular
  3. 3Strangler Fig
  4. 4Microsserviços
  5. 5Database per Service
  6. 6API Gateway

Parecidos

Esc

↑ ↓ navegarEnter abrir239 resultados