🏓API Authentication
Auth0 Actors:
es en realidad de delegar acceso AUTH0, no de dar autenticación, mucho OJO.
Quiz:
Question 1
What was the main problem that led to the inception of OAuth
Companies had too many APIs to expose publicly for basic authentication to suffice
**Companies wanted to expose APIs that used authentication but didn't want 3rd parties to see the user's credentials**
Correct answer.
Companies wanted to create interoperability between APIs
Question 2
The Actors of OAuth 2.0 are
The client, the resource server, the authorization server and the resource holder
**The client, the resource server, the authorization server and the resource owner**
Correct answer.
The client, the resource server and the authorization server
Question 3
Who delegates to who in OAuth
The user delegates to the authorization server
The client delegates to the resource server
**The authorization server delegates to the client**
Correct answer.
OAuth 2.0 Interaction patterns
1. Authorization Code Flow (Code Flow)
Uso común: Aplicaciones web o móviles donde el usuario inicia sesión.
🧩 Resumen:
El usuario se autentica en el authorization server.
Se genera un authorization code.
La app (cliente) intercambia ese código por un access token (y a veces un refresh token).
✅ Ventaja: El token no pasa por el navegador ni la URL directamente, lo que mejora la seguridad.
🔄 2. Refresh Token Flow
Uso común: Para mantener la sesión del usuario sin pedirle que inicie sesión de nuevo.
🧩 Resumen:
Cuando el access token caduca, se usa un refresh token para obtener uno nuevo.
Solo funciona si el flujo inicial (como el code flow) entregó un refresh token.
✅ Ventaja: Mejora la experiencia de usuario al evitar re-autenticaciones.
🔐 3. Client Credentials Flow
Uso común: Comunicación app-to-app o backend-to-backend, sin usuario.
🧩 Resumen:
El cliente (app) se identifica usando su client ID y secret.
El servidor entrega un access token directamente.
No hay usuario final involucrado.
✅ Ventaja: Ideal para APIs internas, microservicios o tareas automatizadas.
Quiz:
Question 1
In the OAuth Code flow, user authentication happens:
Before the user is redirected to the authorization server
After the user has been redirected to the authorization server
Correct answer.
After the user has been redirected back from the authorization server
Question 2
One statement is NOT true about the authorization code
It is returned on the query string to the client in the redirect to the callback endpoint
It is short-lived
It can be used to refresh the access token
Correct answer.
It is bound to the client it was issued to
Question 3
The refresh token is used to
Obtain new access tokens
Correct answer.
Refresh the user's SSO session
Refresh the client's credentials
Question 4
The Client Credentials flow issues:
An authorization code and an access token
An access token and a refresh token
Only an access token
Correct answer.
JSON Web Tokens:
🔐 ¿Qué es un JWT?
Un JSON Web Token (JWT) es un token compacto y auto-contenido usado para transmitir información entre dos partes de forma segura como un access token o ID token.
🧩 1. Formatos
✅ Cómo leer su contenido: Es un string en base64 con tres partes: header, payload y signature.
✅ Cómo validarlo: Usando la firma (normalmente HMAC o RSA), verificás que no haya sido alterado.
🎯 2. Propósito
🔒 ¿Para quién es el token? → Identificado con el claim
aud
(audience).🧠 ¿Cuál es su uso? → Por ejemplo, autenticación, autorización, etc.
🌍 ¿A dónde lo puedo enviar? → Solo a recursos que confíen en el issuer del token.
⚙️ 3. Tipo
⚠️ Palabra sobrecargada, puede referirse al tipo de token (
access
,id
,refresh
) o al tipo de transmisión (Bearer, etc).🚀 ¿Cómo se transmite? → Comúnmente en el header
Authorization: Bearer <token>
.Pero super importante enviarlo bajo canales cifrados, like TLS
Bearer token es como el dinero, si tengo dinero puedo ir a una tienda o donde sea elegir algo y comprarlo con mi cash, en este caso bearer es así, puedo usarlo siempre y cuando esté valido y sea dinero real (metafora), podré usarlo en las auths.
by reference:
Este otro tipo de JWT además del bearer
está POP/HoK
bearer
está POP/HoK
que basicamente son como una tarjeta de credito puedes implementarlo pero debes demostrar que dices ser el usuario que dices ser, pasa tal cual como con las credit card no puedo pagar con una credit card que no es mia y ademas debo financiarle dinero del banco a la tarjeta.
Significa que se deben enviar dos partes de
DPoP
dentro del header Authorization.A JWT IS NOT A PROTOCOL, is a format y no es un type.
Quiz:
Question 1
Which are the three axes used to define a token
Format, purpose and type
Correct answer.
Format, purpose and encoding
Encoding, type and purpose
Encryption, encoding and transport
Question 2
Which of the following statements is NOT true about JWTs
All access tokens are JWTs
Correct answer.
Clients should never decode access tokens, even if they are JWTs
JWTs are not suitable to be sent on the Internet for PII reasons
A JWT consists of three parts, header, payload and signature
Question 3
What is the key benefit of using PoP tokens as access tokens
They are encrypted and cannot be read by anyone but the API
They can only be sent by the client they were issued to
Correct answer.
They point to an entry in the database that only the authorization server can decode
They can be used to obtain more access tokens
Question 4
Access tokens have an audience, what does that mean:
They can only be understood by the entities listed in the audience claim
They can only be sent by an entity listed in the audience claim
They are issued by the entity in the audience claim
They should only be accepted by the entities listed in the audience claim
Correct answer.
Scopes and Claims:
🎯 ¿Qué es un Scope?
Los scopes (alcances) definen qué permisos solicita una aplicación al acceder a una API en nombre de un usuario o cliente.
El server authorization final es el que define si el scope se integra con los issues definidos.
Ejemplo de scopes:
scope=read:user write:posts
🔓 Esto significa:
read:user
: puede leer la info del usuario.write:posts
: puede crear o modificar posts.
🔐 Se usan principalmente durante el OAuth authorization request:
GET /authorize?client_id=abc123&scope=read:user write:posts...
📌 Los scopes limitan lo que puede hacer el token. Son una especie de "contrato" entre el usuario, la app y el API.
🧾 ¿Qué son los Claims?
Los claims son los datos dentro del JWT. Son las piezas de información que se transmiten en el token firmado.
Hay tres tipos:
Registered claims (estándar):
iss
: quién emitió el token.sub
: sujeto (ID del usuario).exp
: fecha de expiración.aud
: audiencia.aud
(de audience) es un claim registrado en los JWT que indica quién está destinado a recibir o consumir ese token.
Es decir, es el identificador de la API o sistema que debe aceptar y validar ese token.
🧠 ¿Por qué es importante?Porque si un token llega a una API que no está en la audiencia, debería ser rechazado. Esto evita que un token válido para un servicio A sea usado indebidamente en un servicio B (replay attacks).
Public claims:
Ej:
name
,email
,picture
.Info general que puede usar el receptor del token.
Private claims:
Claims definidos por tu sistema, como
role
,tenant_id
,plan
.
Ejemplo de payload de JWT:
{
"sub": "1234567890",
"name": "Felipe",
"role": "admin",
"exp": 1712775472
}
Juntando SCOPE CON CLAIM:
Quiz:
Question 1
Which of the following statements is NOT true about scopes
They are used to express client privileges
The client requests a certain set of scopes to be issued in the access token
The scope carries values that are true about the user
Correct answer.
The user may consent to the scopes being issued
Question 2
Why are claims useful to pass in access tokens
They enable the API to make fine grained access control decisions related to the user
Correct answer.
They define policies about which access should be given
They always express the groups the user is in
They are required by the client in order to process the token
#EN ESPAÑOL ->
Pregunta 1
¿Cuál de las siguientes afirmaciones NO es cierta acerca de los scopes
Se utilizan para expresar los privilegios del cliente
El cliente solicita que se emita un determinado conjunto de scopes en el token de acceso
**El scope lleva valores que son verdaderos sobre el usuario**
Respuesta correcta.
El usuario puede dar su consentimiento para que se emitan los ámbitos
Pregunta 2
¿Por qué es útil incluir claims en los tokens de acceso?
**Permiten a la API tomar decisiones de control de acceso detalladas en relación con el usuario.**
Respuesta correcta.
Definen políticas sobre el acceso que se debe otorgar
Siempre expresan los grupos a los que pertenece el usuario
Son requeridas por el cliente para procesar el token
API’s And Gateways:
un API Gateway es como el portero de discoteca de tu sistema de APIs:
🎩 ¿Qué hace?
Recibe todas las solicitudes de los clientes antes de que lleguen a tu backend.
Valida, filtra, transforma o enruta esas solicitudes hacia el microservicio o backend correspondiente.
Puede agregar seguridad, como:
Autenticación y autorización (
Bearer token
, OAuth2, JWT, etc.)Validación de tokens (como en el phantom token flow)
Rate limiting, logging, CORS, etc.
Gateway con Auth0 añadido:
pero añadimos el phantom token flow que es un nuevo pattern añadido:
El Phantom Token Flow es un patrón utilizado principalmente en arquitecturas API Gateway + Resource Server, cuando se usan tokens de acceso opacos (opaque tokens) con OAuth 2.0. Es una técnica para no exponer información sensible de los tokens directamente al cliente.
¿Para qué se usa?Evitar que el token tenga claims sensibles como
email
,roles
,permissions
, etc., en el lado del cliente.Centralizar la validación en el API Gateway.
Simplificar la lógica del backend (no necesita decodificar ni validar tokens).
Api and gateways interactions:
🪙 Token Exchange vs Embed vs Share
1. 🌀 Token Exchange (Intercambio)
¿Qué es? Cambiar un token por otro diferente, pero relacionado.
¿Por qué se hace? Para obtener un token más específico, seguro o con menos privilegios.
Ejemplo típico:
Un cliente obtiene un Access Token del Authorization Server.
Ese token llega al API Gateway.
El Gateway lo intercambia (exchange) por un token interno más restringido (ej. con menos scopes, más corto, etc.), que es el que usa para llamar a servicios internos.
🔒 Evita exponer directamente tokens externos a servicios internos.
Se usa en phantom token flow (el token externo es opaco, el interno es JWT).
2. 📦 Token Embed (Incrustado)
¿Qué es? Incluir (embed) el token en otro objeto o contexto.
¿Dónde se ve?
En un JWT, donde los claims están embebidos directamente (aud, exp, sub, etc.).
En tokens usados dentro de headers de HTTP:
Authorization: Bearer <token>
es una forma de "embed" el token en la solicitud.
Ejemplo visual:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR...",
"token_type": "Bearer",
"expires_in": 3600
}
Token Share (Compartir)
¿Qué es? Usar el mismo token entre distintos componentes.
Riesgo: Cuanto más compartes un token, más superficie de ataque.
Ejemplo:
Un front recibe un token y lo pasa directamente a muchos microservicios.
Si un microservicio se ve comprometido, el token también lo está.
Por eso se evita y se prefiere hacer un exchange o usar phantom token flow.
Introspecti0n, una req valida con todo normal y se manda:
instrospection with exchange, modificamos el content type:
INstrospection, embebemos el JWT dentro del JSON:
instrospection, para intercambiar el token:
Quiz:
Question 1
Which is the standard flow to use in a gateway to know what's inside an opaque token
Interrogation
Introspection
Correct answer.
Inspection
Evaluation
Question 2
The phantom token flow defines a pattern to:
Let an API call another API
Let tokens be exchanged for less powerful tokens
Hide sensitive data on the Internet but expose it internally
Correct answer.
Encrypt JWT tokens
Question 3
There are three methods to use tokens for API to API calls
Exchange, embed, share
Correct answer.
Exchange, swap, share
Exchange, convert, split
Embed, share, re-issue
Question 4
What is good practice for the gateway when it comes to authorization
To evaluate all the token's claims and assure that the request will be successful
To duplicate the logic of the API to be able to make a fine grained authorization decision
To just look at the token validity and let the API make the full authorization decision
To validate the token and inspect the scopes to perform a coarse grained authorization decision
Correct answer.
QUIZ FINAL:
Question 1
Which of the following statements is true about token based architectures
It uses basic authentication to authenticate against APIs
It depends on external token from outside the organization to provide access
It provides fundamentals to build a zero trust architecture
Correct answer.
It requires mutual TLS to be used to provide machine authentication
Question 2
Which HTTP request header is used to pass the access token
The Token header
The Authentication header
The Content-Type header
The Authorization header
Correct answer.
Question 3
What does the client need to send along with an access token of type Bearer when calling the API?
Nothing
Correct answer.
A signature
The refresh token
Question 4
Which OAuth flow is most suitable for web applications
Client Credentials flow
Refresh flow
Web Authentication Flow
Code flow
Correct answer.
Question 5
Who is the only allowed final recipient (audience) of a refresh token?
The Authorization Server
Correct answer.
The API
The Gateway
The client
Question 6
What is the difference between scopes and claims?
Claims don't have values but scopes do
Scopes don't have values but claims do
Correct answer.
Claims can never be issued in the access token but scopes can
Scopes can never be issued in the access token but claims can
Question 7
Why do we say that the access token is the identity API for the APIs
The access token contains claims that can be tailored for the APIs identity needs
Correct answer.
The access token is JWT and therefore developer friendly
The access token is the key for API access
Question 8
What are the two base OAuth endpoints called
Authentication endpoint and token endpoint
Authorization endpoint and token endpoint
Correct answer.
Authorization endpoint and introspection endpoint
Token endpoint and introspection endpoint
Question 9
How does a user authenticate when the client starts a code flow
Using username password
Always using multi factor authentication
According to what the client requests
It is not defined by the OAuth specification
Correct answer.
Question 10
Why are scopes helpful for application (client) level permissions
Because they limit what the client can do, no matter who logs in
Correct answer.
Because they are easy to express in JWTs
Because they contain values that the API can use for fine grained access contro