Skip to content

Authentication

Auth is one decision at puerto nuevo, and the rest follows from it.

puerto nuevo --nombre tienda --db --auth oidc # Auth0, Keycloak or any OpenID Connect provider
puerto nuevo --nombre tienda --db --auth local # accounts and sessions in this database

Both modes share one port, Autenticador, and one Usuario entity in its own context, contextos/usuario/, so the routes, the use cases and the screens are the same either way. GET /api/me answers the caller as the API resolved them. Moving from local accounts to a provider does not touch your domain (ADR-0021).

The API is an OAuth2 resource server: it verifies the provider’s JWT access tokens (RS256 or ES256, iss, aud, exp/nbf) against its JWKS, which is cached and refetched at most once a minute when an unknown kid appears. Auth0 and Keycloak are configuration, not adapters.

The first request of a caller creates their Usuario row (just-in-time provisioning, cached for 60 seconds, in contextos/usuario/infraestructura/src/aprovisionamiento.rs). Roles come from the token only, from the claim AUTH_ROLES_CLAIM names.

.env
AUTH_ISSUER=http://localhost:8180/realms/tienda
AUTH_AUDIENCE=api
AUTH_ROLES_CLAIM=realm_access.roles

For Auth0: AUTH_ISSUER=https://<tenant>.auth0.com/, AUTH_AUDIENCE set to the API identifier, and AUTH_ROLES_CLAIM set to permissions or to the claim an Action adds.

In development, docker-compose.yml runs Keycloak with a realm of its own: a public web client with PKCE, admin@tienda.localhost with the admin role, and user@tienda.localhost without it.

make auth/ui # where the Keycloak console is, and how to sign in
make -s auth/token EMAIL=user@tienda.localhost # an access token, for curl

--auth oidc works without --db too; then the users are kept in memory.

In an auth project every scaffolded route is protected. A handler that takes auth: BearerAuth answers 401 auth.no_autenticado before it runs when the token is missing, unknown or expired. Open routes and role checks are flags of the scaffold:

puerto generar scaffold Producto \
--publico listar_productos,obtener_producto \
--rol borrar_producto=admin \
-- nombre:String precio:i64 sku:String!
contextos/producto/rest/src/rutas.rs (excerpt)
/// Borra: Producto
#[oai(path = "/productos/:id", method = "delete", tag = "ApiTags::Producto")]
#[requiere_rol("admin")]
async fn borrar(&self, auth: BearerAuth, id: Path<Uuid>) -> RespuestaBorrarProducto {
match self
.borrar_producto
.ejecutar(ParamsBorrarProducto {
actor: auth.0,
id: IdProducto::from_uuid(id.0),
})
.await
// …

#[requiere_rol("admin")] adds a 403 auth.prohibido check at the top of the handler. Two roles on one route mean the caller needs both. The flags land in puerto.toml:

[[entidad]]
nombre = "Producto"
publicos = ["listar_productos", "obtener_producto"]
[entidad.roles]
borrar_producto = ["admin"]

puerto validar checks that rutas.rs still says the same as the manifest. Change both together.

“Only the owner can edit it” is not an attribute: it depends on the row. Protected use cases receive the caller as actor: Principal (id_usuario, sujeto, email, nombre, roles) and decide. With a propietario:Uuid field on the entity:

if producto.propietario != params.actor.id_usuario {
return Err(ErrorProducto::Prohibido); // 403 producto.prohibido
}

The domain sees a Principal, never a token. Tests build one with puerto_nucleo::auth::dobles::MadrePrincipal, and route tests sign in with a MockAutenticador.

useAuth() gives { user, can(role), login, logout }, where user comes from GET /me. The generated route table wraps every non-public screen in <RequireAuth>, which sends whoever is not signed in to sign in, as a 401 from any call does. Generated screens hide the actions the user’s roles do not allow, but the API decides: its 403 reaches the alert as auth.prohibido.

OIDC Local
Sign in Authorization Code + PKCE (oidc-client-ts) /login and /register pages
Token kept in memory; a reload goes back through the provider localStorage; Sign out revokes it
Status Code When
401 auth.no_autenticado no token, or an invalid or expired one
401 auth.credenciales_invalidas local login with a wrong email or password
403 auth.prohibido the caller lacks a role #[requiere_rol] asks for
403 <entidad>.prohibido a use case’s own rule refused the caller (producto.prohibido)
409 usuario.duplicado local registration with an email that already has an account
422 usuario.validacion.email_invalido, usuario.validacion.contrasena_demasiado_corta local registration with a bad email or a password under 12 characters
503 auth.no_disponible the provider could not be reached