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 providerpuerto nuevo --nombre tienda --db --auth local # accounts and sessions in this databaseBoth 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.
AUTH_ISSUER=http://localhost:8180/realms/tiendaAUTH_AUDIENCE=apiAUTH_ROLES_CLAIM=realm_access.rolesFor 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 inmake -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.
The API is the identity provider. It needs --db.
| Route | Does |
|---|---|
POST /api/auth/registro |
creates an account from email, contrasena (12 characters at least) and an optional nombre; 201 with the user |
POST /api/auth/login |
takes email and contrasena, answers an opaque session: token and expiraEn |
POST /api/auth/logout |
revokes the session the request is signed with; 204 |
GET /api/me |
the caller, as the API resolved them: id, email, nombre, roles |
Passwords are argon2id hashes in credenciales, so Usuario carries no secret. A session token
is 256 random bits, and sesiones keeps only its SHA-256. Revoking one is a DELETE, and there
is no signing key to rotate. An unknown email and a wrong password get the same
401 auth.credenciales_invalidas, in the same time.
AUTH_SESSION_TTL=30d # 30d, 12h, 90mRoles are the usuarios.roles column, and they apply from the next request:
make auth/conceder EMAIL=ada@example.com ROL=adminRegistration is open. registrar_usuario, login and logout
(contextos/usuario/aplicacion/src/) and contextos/usuario/rest/src/auth/ are yours: close
registration or add rules there.
Protected by default
Section titled “Protected by default”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!/// 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.
Rules that depend on data
Section titled “Rules that depend on data”“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.
The frontend
Section titled “The frontend”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 |
Errors
Section titled “Errors”| 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 |