pattern/security/federated-identity
- Bun
- ElysiaJS
- PostgreSQL
- TypeScript
- node-postgres
- node:crypto
- Docker
A autenticação fica com o dono da identidade: o cliente consente no banco (IdP) e a fintech (RP) recebe só um token com escopo e prazo, nunca a senha. Authorization code flow OAuth 2 + PKCE, base do Open Finance.
pattern/security/federated-identity
Cenário
O cliente conecta a fintech à conta; a fintech troca o código por um token accounts:read e lista as contas.
Planta
Sequência7 passos — reproduza para seguir o fluxo
Como funciona
4passos
Authorization code flow OAuth 2 com PKCE: o IdP autentica e a aplicação recebe só um token com escopo e prazo
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
Redireciona ao banco com state e code_challenge S256
O banco confere redirect_uri exato e escopo; devolve código de uso único
A fintech troca código com client_secret e code_verifier; código queimado num UPDATE
Códigos e tokens só como SHA-256; recurso exige o escopo da rota
Trade-offs
O que se ganha, o que se paga
Vantagens
Fintech nunca vê a senha
Token com escopo e prazo
Custos
Mais idas e voltas que login local
Banco é dependência de toda conexão
Código
pattern/security/federated-identity
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec federated-identity-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f federated-identity-dbSaída: o banco redireciona ao /callback com código e state conferido; a fintech recebe token accounts:read e GET /open-finance/accounts → 200 com as contas 0001-77008800 e 0001-77008801.
Código
src/demo.ts// Demo: Open Finance — the customer consents at the bank; the fintech gets a code, trades it with PKCE for a scoped
// token, and reads the accounts without ever seeing the customer's password.
import { createHash, randomBytes } from "node:crypto";
import { Elysia, t } from "elysia";
import pg from "pg";
const pool = new pg.Pool({ connectionString: Bun.env.FEDERATED_IDENTITY_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/federated_identity_db" });
const CLIENT = { id: "fintech-parceira", secret: Bun.env.FEDERATED_IDENTITY_CLIENT_SECRET ?? "fintech-parceira-secret-7f3a", redirectUri: "http://localhost:8707/callback" };
const CODE_TTL_SECONDS = 60;
const ACCESS_TOKEN_TTL_SECONDS = 5 * 60;
const sha256Hex = (value: string) => createHash("sha256").update(value).digest("hex");
const tokenNew = () => randomBytes(32).toString("base64url");
// PKCE: the fintech keeps the verifier; only its S256 challenge travels through the browser.
const pkceChallenge = (verifier: string) => createHash("sha256").update(verifier).digest("base64url");
// The bank as identity provider and resource server. Codes and tokens are stored as SHA-256 only.
const bank = new Elysia()
// The customer, already logged in at the bank, approves the consent: the code goes back through the browser.
.get("/authorize", async ({ query, redirect, status }) => {
const { rows } = await pool.query<{ redirect_uri: string; allowed_scopes: string[] }>("SELECT redirect_uri, allowed_scopes FROM clients WHERE client_id = $1", [query.client_id]);
// Exact redirect match: a lax comparison lets an attacker receive the code.
if (!rows[0] || rows[0].redirect_uri !== query.redirect_uri || !rows[0].allowed_scopes.includes(query.scope)) return status(400, "invalid client, redirect_uri or scope");
const code = tokenNew();
await pool.query("INSERT INTO authorization_codes (code_hash, client_id, customer_id, scope, code_challenge, expires_at) VALUES ($1, $2, 'cust-001', $3, $4, now() + make_interval(secs => $5))", [sha256Hex(code), query.client_id, query.scope, query.code_challenge, CODE_TTL_SECONDS]);
return redirect(`${query.redirect_uri}?${new URLSearchParams({ code, state: query.state })}`, 302);
}, { query: t.Object({ client_id: t.String(), redirect_uri: t.String(), scope: t.String(), state: t.String(), code_challenge: t.String({ minLength: 43 }) }) })
// Server to server: client secret, PKCE verifier, and the code burnt in one statement — a replay finds nothing.
.post("/token", async ({ body, status }) => {
const { rows } = await pool.query<{ customer_id: string; scope: string; code_challenge: string }>(`UPDATE authorization_codes a SET used_at = now() FROM clients c WHERE a.code_hash = $1 AND a.used_at IS NULL AND a.expires_at > now() AND c.client_id = a.client_id AND c.client_id = $2 AND c.secret_hash = $3 RETURNING a.customer_id, a.scope, a.code_challenge`, [sha256Hex(body.code), body.client_id, sha256Hex(body.client_secret)]);
if (!rows[0] || pkceChallenge(body.code_verifier) !== rows[0].code_challenge) return status(400, { error: "invalid_grant" });
const accessToken = tokenNew();
await pool.query("INSERT INTO access_tokens (token_hash, customer_id, scope, expires_at) VALUES ($1, $2, $3, now() + make_interval(secs => $4))", [sha256Hex(accessToken), rows[0].customer_id, rows[0].scope, ACCESS_TOKEN_TTL_SECONDS]);
return { access_token: accessToken, token_type: "Bearer", scope: rows[0].scope };
}, { body: t.Object({ code: t.String(), client_id: t.String(), client_secret: t.String(), code_verifier: t.String() }) })
.get("/open-finance/accounts", async ({ headers, status }) => {
const { rows } = await pool.query<{ customer_id: string }>("SELECT customer_id FROM access_tokens WHERE token_hash = $1 AND scope = 'accounts:read' AND expires_at > now()", [sha256Hex(headers.authorization?.replace(/^Bearer /, "") ?? "")]);
if (!rows[0]) return status(401, "invalid token");
return (await pool.query<{ id: string }>("SELECT id FROM accounts WHERE customer_id = $1 ORDER BY id", [rows[0].customer_id])).rows;
});
const bankCall = (path: string, init?: RequestInit) => bank.handle(new Request(`http://bank${path}`, init));
// The fintech as relying party: state against CSRF, verifier kept on its side, secret sent only server to server.
const state = tokenNew();
const verifier = tokenNew();
const authorize = await bankCall(`/authorize?${new URLSearchParams({ client_id: CLIENT.id, redirect_uri: CLIENT.redirectUri, scope: "accounts:read", state, code_challenge: pkceChallenge(verifier) })}`);
const callback = new URL(authorize.headers.get("location") ?? "");
if (callback.searchParams.get("state") !== state) throw new Error("state mismatch");
console.log(` [BROWSER] bank → ${callback.origin}${callback.pathname}?code=…&state=ok`);
const token = (await (await bankCall("/token", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code: callback.searchParams.get("code"), client_id: CLIENT.id, client_secret: CLIENT.secret, code_verifier: verifier }) })).json()) as { access_token: string; scope: string };
console.log(` [FINTECH] token with scope ${token.scope}`);
const accounts = await bankCall("/open-finance/accounts", { headers: { authorization: `Bearer ${token.access_token}` } });
console.log(` [FINTECH] GET /open-finance/accounts → ${accounts.status} ${await accounts.text()}`);
await pool.end();
Nível
avançado
8/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Trilhapasso 3 de 6
Segurança de API bancária
Parecidos
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Federated Identity?
Verifica em cada salto. Abrir Zero Trust
Seu progresso
0/157 estudados
Fica salvo só neste navegador.