Identidad y acceso
OAuth 2.0 / OpenID Connect
OAuth2 delega AUTORIZACIÓN (acceso a APIs); OIDC agrega AUTENTICACIÓN (id_token: quién es el usuario).
Para decir en una reunión"Para la SPA y la app móvil: Authorization Code con PKCE contra el IdP (ej. Keycloak). El flujo implícito está deprecado."
Lo esencial
- Roles: Resource Owner (usuario), Client (tu app), Authorization Server (IdP), Resource Server (API).
- Flujos: Authorization Code + PKCE (apps web/móviles/SPA), Client Credentials (máquina a máquina), Device Code (TVs/CLI).
- state contra CSRF en el login, nonce contra replay del id_token, redirect_uri exacta registrada.
- OAuth 2.1 consolida estas buenas prácticas: PKCE obligatorio, sin implicit ni password grant.
- Patrón BFF (Backend for Frontend): el token nunca llega al navegador.
❌ Lo que sale mal
- Usar OAuth2 para "login" y leer la identidad del
access_token(es para APIs). - Implementar el flujo Implicit o sin PKCE en apps públicas.
- No validar
state(CSRF) ni elredirect_uricontra una allowlist exacta.
✅ Cómo se hace bien
- Para identidad usar OIDC y el
id_token; OAuth2 solo autoriza acceso a recursos. - Authorization Code + PKCE para web y móvil (Implicit está deprecado).
- Validar
state,nonceyredirect_uricon match exacto.
La pregunta trampa
¿OAuth2 sirve para autenticar usuarios?
No por sí solo: un access token no dice quién está logueado ni para quién fue emitido. Para eso está OIDC y su id_token.
✅ PKCE en el cliente
const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
const challenge = base64url(new Uint8Array(hash));
sessionStorage.setItem("pkce", verifier);
location.href = AUTH + "/authorize?response_type=code&client_id=app"
+ "&code_challenge=" + challenge + "&code_challenge_method=S256"
+ "&state=" + estadoAleatorio
+ "&redirect_uri=" + encodeURIComponent(REDIRECT);