Pular para o conteúdo

Federated Identity

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.

passos
4
arquivos
7
testes
0
tecnologias
7

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ência
7/7
redireciona para /authorize (state, code_challenge S256)1GET /authorize com a sessão do banco2302 para /callback?code&state3GET /callback4POST /token (code, client_secret, code_verifier)5access_token com escopo accounts:read6GET /open-finance/accounts (Bearer)7Fintech (relying party)Navegador do clienteBanco (identity provider)
7

7 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.

  1. 1

    Redireciona ao banco com state e code_challenge S256

  2. 2

    O banco confere redirect_uri exato e escopo; devolve código de uso único

  3. 3

    A fintech troca código com client_secret e code_verifier; código queimado num UPDATE

  4. 4

    Códigos e tokens só como SHA-256; recurso exige o escopo da rota

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

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

sql/

  • 01_schema.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec federated-identity-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f federated-identity-db

Saí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.

Requisitos
BunDocker
Sobe junto
PostgreSQL

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

Linhas de TypeScript
50
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • Conta corrente

Padrões do catálogo que implementa

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • customers
  • clients
  • authorization_codes
  • access_tokens
  • accounts

Variáveis de ambiente

FEDERATED_IDENTITY_DATABASE_URL
postgres://postgres:postgres@localhost:5432/federated_identity_db
FEDERATED_IDENTITY_CLIENT_SECRET
fintech-parceira-secret-7f3a

Trilhapasso 3 de 6

Segurança de API bancária

  1. 1API Key Management
  2. 2Token Auth
  3. 3Federated Identity
  4. 4Zero Trust
  5. 5Gerenciamento de Segredos
  6. 6Audit Log

Parecidos

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Federated Identity?

Próximo projeto, Segurança & AuditoriaGatekeeper
Esc

↑ ↓ navegarEnter abrir239 resultados