# Who > Identity and permissions for Spring Boot applications. who is a Spring Boot 4 library: add the starter and a module per sign-in method, and an app gets passwordless sign-in by emailed link or code, passkeys, Google, GitHub or OpenID Connect sign-in, API keys and JWTs, all resolving to one identity with roles and permissions checked by `@RequiresPermission`. Maven coordinates: `org.jwcarman.who`; import `who-bom` and add `who-spring-boot-starter` plus the modules you want. The changelog says what each version has: https://github.com/jwcarman/who/blob/main/CHANGELOG.md. API reference (Javadoc): https://jwcarman.github.io/who/api/latest/. An Agent Skill packages these guides for coding agents: see the Agent Skill page. # Start here # Who Identity and permissions for Spring Boot applications. Java 25+ · Spring Boot 4.1+ · PostgreSQL 14+ [Get started](https://jwcarman.github.io/who/guides/getting-started/index.md) [View on GitHub](https://github.com/jwcarman/who) Who maps the credentials a caller presents (a JWT, an API key) to one stable internal identity, and resolves that identity's permissions. Your controllers check permission strings. They do not know which credential the caller used. ``` @GetMapping("/tasks") @RequiresPermission("task.read") public List getTasks(@AuthenticationPrincipal WhoPrincipal principal) { return taskService.findAll(principal.identity().id()); } ``` ## How it works Every request goes through this pipeline: ``` HttpRequest → Credential → Identity → Set permissions → WhoPrincipal ``` - A **credential** is something a caller presents: the `(iss, sub)` pair of a validated JWT, or an API key. Who stores credentials and links each one to an identity. - An **identity** is a UUID with a status. One identity can have many credentials. Only `ACTIVE` identities authenticate. - A **permissions resolver** loads the identity's permission strings. With `who-rbac`, permissions come from the roles assigned to the identity. - The resulting `WhoPrincipal` goes into the Spring Security context, and `@RequiresPermission` checks it. Who does not auto-provision. A credential that is not linked to an identity is denied. You link credentials with an [enrollment](https://jwcarman.github.io/who/guides/enrollment/index.md) flow, or by creating them yourself. ## What you get - **JWT resource servers** ______________________________________________________________________ `WhoJwtAuthenticationConverter` turns a validated JWT into a `WhoPrincipal`. See [JWT](https://jwcarman.github.io/who/guides/jwt/index.md). - **Social login** ______________________________________________________________________ Sign in with Google, GitHub or any OpenID Connect provider. Sign-up is closed until your policy opens it, and nothing links by email. See [Social Login](https://jwcarman.github.io/who/guides/social-login/index.md). - **API keys** ______________________________________________________________________ Keys expire, hold only the permissions they were scoped to, record their last use, and rotate with an overlap. They are hashed before storage and shown once. See [API Keys](https://jwcarman.github.io/who/guides/api-keys/index.md). - **Enrollment** ______________________________________________________________________ Single-use, expiring tokens that link a user's credential to an identity you created. See [Enrollment](https://jwcarman.github.io/who/guides/enrollment/index.md). - **Roles and permissions** ______________________________________________________________________ `RbacService` manages roles. `@RequiresPermission` is enforced by default. See [RBAC and Method Security](https://jwcarman.github.io/who/guides/rbac/index.md). ## Examples Runnable apps, one for each kind of app built on who, in [`who-examples`](https://github.com/jwcarman/who/tree/main/who-examples). Each starts what it needs with Spring Boot's Docker Compose support. - [Web app](https://github.com/jwcarman/who/tree/main/who-examples/web-app): server-rendered pages with email links, passkeys and social login on who's default chain. - [Single-page app](https://github.com/jwcarman/who/tree/main/who-examples/spa): the same app in React and TypeScript over a JSON backend, built by Maven into the jar or run on Vite's dev server. - [API](https://github.com/jwcarman/who/tree/main/who-examples/api): the board as a stateless JSON API, called with access tokens from Keycloak and with API keys, which people make and revoke through it. - [Website and API](https://github.com/jwcarman/who/tree/main/who-examples/web-and-api): one app that is both, with a security chain for each: sessions and CSRF for the pages, `WhoSecurity.stateless()` for `/api/**`. People manage their API keys on the website. - [Observability](https://github.com/jwcarman/who/tree/main/who-examples/observability): who's meters, traces and logs in Grafana's LGTM stack, with a provisioned dashboard, a traffic generator, and a page whose every request links to its trace and log lines. ## Modules | Module | What it is | | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `who-core` | Domain types (`Identity`, `WhoPrincipal`), service and SPI interfaces. Needs no Spring at runtime; `WhoService`'s `@Transactional` applies when Spring's transaction support is present (always, with who's starter) | | `who-jdbc` | JDBC repositories, using Spring `JdbcClient` | | `who-rbac` | `RbacService` and a `PermissionsResolver` backed by roles and permissions | | `who-federated` | `FederatedCredential`, the `(issuer, subject)` credential that JWT and provider sign-in share, and `FederatedCredentialService` | | `who-jwt` | `WhoJwtAuthenticationConverter` | | `who-oidc` | Sign-in with Google, GitHub or any OpenID Connect provider, on Spring's `oauth2Login`: `WhoSignUpPolicy` decides who may sign up | | `who-apikey` | `ApiKeyAuthenticationFilter` and `ApiKeyService` | | `who-enrollment` | `WhoEnrollmentService`, for issuing and redeeming enrollment tokens | | `who-admin` | Admin endpoints for identities, roles and invitations, guarded by `who.identities.read` and `who.identities.manage`; brings `who-rbac` | | `who-email-link` | Email sign-in with a link or a typed code: `EmailCredentialService`, `WhoEmailSender`, `EmailLinkMessage`, and the hooks for Spring's one-time-token login | | `who-turnstile` | Cloudflare Turnstile as the human check on who's email endpoints: `TurnstileHumanCheck` | | `who-passkey` | Passkey sign-in: `PasskeyService`, `PasskeyAddedNotifier`, and the hooks for Spring's WebAuthn login | | `who-spring-security` | `@RequiresPermission`, `WhoSecurity.all()`, `WhoWebSecurity.passwordless()`, `GET /who/me` and `GET /who/sign-in` | | `who-autoconfigure` | Spring Boot autoconfiguration for all modules | | `who-spring-boot-starter` | Starter with the base: `who-core`, `who-spring-security`, `who-jdbc`, `who-rbac` and the autoconfiguration. Add each sign-in module you use; its jar turns it on | # Getting Started ## Requirements - Java 25+ - Spring Boot 4.1+ (Who is built against 4.1.2) - PostgreSQL 14+ required. It is the database Who is tested against. ## Run the example app To see every browser sign-in method working together, run the [web app example](https://github.com/jwcarman/who/tree/main/who-examples/web-app): with Docker running, `./mvnw spring-boot:run -pl who-examples/web-app` starts it with its Postgres, Mailpit and Keycloak. The [single-page app example](https://github.com/jwcarman/who/tree/main/who-examples/spa) is the same app in React over a JSON backend. The [API example](https://github.com/jwcarman/who/tree/main/who-examples/api) is the same board as a stateless JSON API, called with access tokens from Keycloak and with who API keys. Clone the repository and start it: ``` git clone https://github.com/jwcarman/who cd who ./mvnw install -DskipTests ./mvnw spring-boot:run -pl who-examples/api ``` Its README gets a token with `curl` and walks through the calls, as `alice` (an admin), `bob` (a member) and `carol` (who has a Keycloak account but no who identity, so her token gets `401`). ## Add the dependency Import the BOM so that every who module uses the same version: ``` org.jwcarman.who who-bom 0.24.0 pom import ``` Then add the starter, each sign-in method you use, and `who-test` for your tests, with no versions: ``` org.jwcarman.who who-spring-boot-starter org.jwcarman.who who-email-link org.jwcarman.who who-email org.jwcarman.who who-email-smtp org.jwcarman.who who-test test ``` The starter brings the base: identities, sessions, permissions and the autoconfiguration. Each sign-in method is its own module, and adding its jar turns it on: | Sign-in method | Module | Guide | | --------------------------------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | Emailed link or typed code | `who-email-link`, with `who-email` and a sender | [Email Links](https://jwcarman.github.io/who/guides/email-links/index.md), [Email](https://jwcarman.github.io/who/guides/email/index.md) | | Passkey | `who-passkey` | [Passkeys](https://jwcarman.github.io/who/guides/passkeys/index.md) | | API key | `who-apikey` | [API Keys](https://jwcarman.github.io/who/guides/api-keys/index.md) | | JWT from your authorization server | `who-jwt` | [JWT](https://jwcarman.github.io/who/guides/jwt/index.md) | | Google, GitHub or any OpenID Connect provider | `who-oidc` | [Social Login](https://jwcarman.github.io/who/guides/social-login/index.md) | `who-enrollment` adds [enrollment tokens](https://jwcarman.github.io/who/guides/enrollment/index.md), and `who-admin` [endpoints for managing identities, roles and invitations](https://jwcarman.github.io/who/guides/admin/index.md). The BOM manages only who's own artifacts, not Spring Boot's versions. A module that needs settings fails startup until it has them, and the report says what to set, for example: ``` *************************** APPLICATION FAILED TO START *************************** Description: who cannot start: who.email-link.link-base-url must be set to the page that receives sign-in links. Action: Set it to the URL of your sign-in page, such as https://app.example.com/signin. Or turn email-link sign-in off with who.email-link.enabled=false. ``` `who..enabled=false` turns a module off without removing its jar. See the [Configuration Reference](https://jwcarman.github.io/who/guides/configuration/index.md). ## Secure the app With no `SecurityFilterChain` of your own, who registers one in place of each default chain Spring Boot would register (form login, the resource server's, Actuator's, `oauth2Login`'s). It mounts every sign-in method on the classpath and answers a signed-out request with `401` (as a `NotSignedInException`, so your `@RestControllerAdvice` can shape it; see [Errors](https://jwcarman.github.io/who/guides/errors/index.md)). There is no login page and no redirect. Signed-out requests may reach only: - `/error`; - `GET /who/sign-in`, which tells a sign-in page which methods are on; - each sign-in method's endpoints, such as `/who/email/send` and `/who/email/sign-in`; - Actuator's health endpoint, if Actuator is present; - the paths you list in `who.security.public-paths`, and those any `WhoPublicPathContributor` bean adds (see [Configuration](https://jwcarman.github.io/who/guides/configuration/index.md)). List your own sign-in page and the assets it loads there, including the page `who.email-link.link-base-url` points at: ``` who: security: public-paths: - /signin - /assets/** ``` When a browser sign-in method (email link or passkey) is present, the chain protects against CSRF with Spring's `csrf.spa()`. A request with a bearer token or an API key and no session is exempt: the token or key signs it in or it gets `401`. A request with a session ignores the token or key and keeps its CSRF check. With only API keys or JWTs, who gives no request a session, so the chain checks CSRF only on requests that bring one, and a signed-out client can post to a public path. ### Your own chain Define any `SecurityFilterChain` and who's chain backs off; Spring Boot's rule. To keep who's sign-in methods in a chain of your own, mount them all with `WhoSecurity.all()`, and open the same paths with `WhoPublicPaths`: ``` @Bean SecurityFilterChain chain(HttpSecurity http, WhoPublicPaths publicPaths) { http.with(WhoSecurity.all(), Customizer.withDefaults()) .authorizeHttpRequests(a -> a .requestMatchers(publicPaths.patterns()).permitAll() .anyRequest().authenticated()); return http.build(); } ``` Or wire one method at a time, as each method's guide shows: `WhoWebSecurity.passwordless()` for email links and passkeys, `WhoApiKeySecurity.apiKey()` for API keys, and Spring's `oauth2ResourceServer()` with `WhoJwtAuthenticationConverter` for JWTs. ### A website and an API The most common reason for chains of your own is an app that is both a website for people and an API for machines. The website needs sessions and CSRF; the API needs neither, and must not accept a browser's session cookie. Give each its own chain, the API's first: ``` @Bean @Order(1) SecurityFilterChain api(HttpSecurity http) { http.securityMatcher("/api/**") .with(WhoSecurity.stateless(), Customizer.withDefaults()) .authorizeHttpRequests(a -> a.anyRequest().authenticated()); return http.build(); } @Bean @Order(2) SecurityFilterChain web(HttpSecurity http, WhoPublicPaths publicPaths) { http.with(WhoWebSecurity.passwordless(), Customizer.withDefaults()) .authorizeHttpRequests(a -> a .requestMatchers(publicPaths.patterns()).permitAll() .anyRequest().authenticated()); return http.build(); } ``` `WhoSecurity.stateless()` mounts only who's token and key sign-in (`who-jwt`, `who-apikey`), never a browser method, into a chain that: - never reads or creates a session, so a session cookie, who's or Spring's own, signs nothing in on the API and a signed-out call starts none; - has no CSRF protection, because nothing it accepts rides along with a request by itself: a forged cross-site request cannot add the header a token or key travels in; - answers a signed-out request with `401` and a denied one with `403`, through your `@RestControllerAdvice` like every who error; the `401` carries `WWW-Authenticate: Bearer` when JWTs are on. With neither `who-jwt` nor `who-apikey` on, startup fails. The [web-and-api example](https://github.com/jwcarman/who/tree/main/who-examples/web-and-api) is this app, runnable. ## Create an identity `WhoService` is the entry point for creating identities. Do not write to `IdentityRepository` directly. ``` @Autowired WhoService whoService; // A new ACTIVE identity with a generated UUIDv7 Identity identity = whoService.createIdentity(); UUID identityId = identity.id(); ``` Everything else (enrolling credentials, assigning roles, issuing API keys) takes an identity created this way. ## Deleting an identity Delete identities through `WhoService` too: ``` boolean deleted = whoService.deleteIdentity(identityId); // false if there is no such identity ``` In one transaction, it deletes each of the identity's email, JWT and API key credentials, unlinks them, and deletes the identity. Its role assignments, enrollment tokens and passkeys go with it. Do not run `DELETE FROM who_identity` yourself. Credential rows do not reference their identity, so a raw delete removes only the links and leaves the credential rows behind. `EmailCredentialService.register` lets the next identity register such an orphaned address: it deletes the old credential, with any sign-in link sent to the deleted user, and registers a new one. To clean them up, call: ``` int removed = whoService.purgeOrphanedCredentials(); ``` It deletes every credential linked to no identity, including credentials that are unlinked only for now. A JWT credential saved for [enrollment](https://jwcarman.github.io/who/guides/enrollment/index.md) is unlinked until the user enrolls, and a credential being registered (an API key, say) is unlinked between being saved and being linked. Run the purge when no enrollment or registration is in flight. If you replace one of who's credential repository beans, `deleteIdentity` and the purge skip that module's rows unless your bean also implements `CredentialRemover` (and is declared with a type that includes it). ## Next steps 1. [Database Setup](https://jwcarman.github.io/who/guides/database/index.md): create Who's tables. 1. [Email Links](https://jwcarman.github.io/who/guides/email-links/index.md), [Passkeys](https://jwcarman.github.io/who/guides/passkeys/index.md), [API Keys](https://jwcarman.github.io/who/guides/api-keys/index.md) or [JWT](https://jwcarman.github.io/who/guides/jwt/index.md): set up each sign-in method you added. 1. [Enrollment](https://jwcarman.github.io/who/guides/enrollment/index.md): link a user's credential to an identity. 1. [RBAC and Method Security](https://jwcarman.github.io/who/guides/rbac/index.md): grant permissions and check them. # Configuration Reference | Property | Default | Description | | ------------------------------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `who.base-path` | `/who` | The root of every who endpoint: `/sign-in`, `/me/...`, `/logout`, `/email/...`, `/passkey/...`, `/oidc/...` (including the provider callback), and who-admin's `/identities`, `/roles` and `/invitations`. A path that starts with `/`, does not end with `/`, is not `/` alone, and holds no `*{}?#;` or whitespace; anything else fails startup. See [Endpoints](#endpoints) | | `who.initialize-schema` | `embedded` | When to run Who's bundled DDL scripts: `always`, `embedded` (H2/HSQLDB/Derby only), or `never` | | `who.security.public-paths` | none | Paths of your app that who's default chain opens to signed-out requests, such as `/signin` and `/assets/**`. `/error`, `/sign-in`, the sign-in methods' endpoints and Actuator's health endpoint are open already. A library or your app can add paths in code with a `WhoPublicPathContributor` bean (`Collection publicPaths()`, patterns from the app's root, matched the same way; a null or blank one fails startup, naming the bean). Contributions only add: they cannot remove a path. All of them are in the `WhoPublicPaths` bean for a chain of your own. An application that defines its own `WhoPublicPaths` bean replaces who's, and with it every contribution | | `who.email-link.enabled` | `true` | Turns email-link sign-in off when `false`, with `who-email-link` still on the classpath | | `who.passkey.enabled` | `true` | Turns passkeys off when `false`, with `who-passkey` still on the classpath | | `who.api-key.enabled` | `true` | Turns API keys off when `false`, with `who-apikey` still on the classpath | | `who.jwt.enabled` | `true` | Turns JWT sign-in off when `false`, with `who-jwt` still on the classpath. When Spring Boot builds the decoder, `spring.security.oauth2.resourceserver.jwt.audiences` is required | | `who.turnstile.enabled` | `true` | Turns the Turnstile human check off when `false`, with `who-turnstile` still on the classpath | | `who.oidc.enabled` | `true` | Turns provider sign-in off when `false`, with `who-oidc` still on the classpath | | `who.enrollment.enabled` | `true` | Turns enrollment tokens off when `false`, with `who-enrollment` still on the classpath | | `who.admin.enabled` | `true` | Turns who's [admin endpoints](https://jwcarman.github.io/who/guides/admin/index.md) off when `false`, with `who-admin` still on the classpath | | `who.enrollment.token-expiration` | `24h` | How long a newly issued enrollment token is valid (ISO-8601 duration, e.g. `PT12H`) | | `who.security.recent-sign-in` | `10m` | How recently a browser session must have signed in to add or remove a way to sign in (a passkey, a provider account, an email address), to [end another session](https://jwcarman.github.io/who/guides/sessions/#see-and-end-sessions), to make or rotate an [API key](https://jwcarman.github.io/who/guides/account/#api-keys), to change identities through the [admin endpoints](https://jwcarman.github.io/who/guides/admin/index.md), and to call an action marked [`@RequiresRecentSignIn`](https://jwcarman.github.io/who/guides/security-model/#recent-sign-in) without a window of its own. Checked when the request starts and when it is confirmed; a started provider link lasts as long | | `who.security.last-sign-in-cookie.enabled` | `true` | Sets the `who_last_sign_in` cookie after a browser sign-in. See [Sessions](https://jwcarman.github.io/who/guides/sessions/#the-last-sign-in-cookie) | | `who.sessions.auto-purge` | `true` | Each sign-in deletes one batch of ended or abandoned session records. Set to `false` to call `WhoSessions.purgeEndedSessions()` on a schedule of your own. See [Sessions](https://jwcarman.github.io/who/guides/sessions/#purging-old-rows) | | `who.sessions.purge-batch-size` | `100` | The most session records one purge deletes. Positive, or startup fails | | `who.sessions.last-seen-interval` | `5m` | How often, at most, a session's last use is written. Positive, or startup fails. How long a session lasts without a request is `spring.session.timeout` with Spring Session, else `server.servlet.session.timeout`, read as Spring Boot reads them (a bare number is seconds, an empty value is unset). Since a busy session's last use can lag by up to this interval, who treats a record as abandoned only after the timeout plus this interval | | `who.method-security.enabled` | `true` | Enables method security so `@RequiresPermission` is enforced. Set to `false` to turn it off, for instance to configure `@EnableMethodSecurity` yourself. `@RequiresRecentSignIn` is enforced either way | | `who.api-key.header-name` | `X-API-Key` | HTTP header used to pass API keys | | `who.api-key.prefix` | `who_` | Starts every new API key, so secret scanners can spot one. Letters, digits and `_`, 2 to 20 characters, ending in `_`, or startup fails. Changing it leaves existing keys working | | `who.api-key.max-lifetime` | `365d` | The longest lifetime a new API key may be given. Positive, or startup fails | | `who.api-key.last-used-interval` | `5m` | How often, at most, an API key's last use is written. Positive, or startup fails | | `who.email.from` | none | The address every who email comes from. Required with `who-email-smtp` once a `JavaMailSender` exists; startup fails without it. See [Email](https://jwcarman.github.io/who/guides/email/index.md) | | `who.email.templates` | `classpath:/templates/who/email/` | Where your email templates are: a list of locations, searched in order before any library's and who's own. `sign-in.txt` there replaces who's sign-in text; `sign-in.html` adds HTML | | `who.email.locale` | the JVM's | The locale emails are rendered in when no request's locale is known | | `who.email.model.*` | none | Values every email template sees, as `{{app.}}` | | `who.email-link.link-base-url` | none | Page of your app that receives sign-in links. The token is appended as `#token=...`. Required with `who-email-link`: a missing or blank value fails startup. List the page in `who.security.public-paths` | | `who.email-link.token-ttl` | `5m` | How long a sign-in link stays valid | | `who.email-link.resend-interval` | `60s` | Minimum time between two links for the same address. Startup fails if it is longer than `token-ttl` | | `who.email-link.address-confirmation-url` | `link-base-url` | Page of your app that receives the link confirming an address being added or changed. The token is appended as `#confirm-address=...`. The person must be signed in there | | `who.email-link.code-length` | `6` | Number of characters in the typed sign-in code. At least 6 | | `who.email-link.code-max-attempts` | `5` | Wrong guesses a sign-in code survives before it is burnt. The link still works. At least 1 | | `who.email-link.code-secret` | none | Secret that keys the code hash. Required with `who-email-link`, at least 32 characters, the same on every instance. Never stored in the database | | `who.turnstile.secret-key` | none | The Turnstile widget's secret key. Required with `who-turnstile`: a missing, blank or unresolved value fails startup. See [Human check](https://jwcarman.github.io/who/guides/email-links/#human-check) | | `who.turnstile.verify-url` | `https://challenges.cloudflare.com/turnstile/v0/siteverify` | Where tokens are verified. Point it at a stand-in, such as WireMock, in tests. An absolute `http` or `https` URL; anything else fails startup | | `who.turnstile.hostnames` | none | Hostnames a Turnstile token may be made on. Empty accepts any | | `who.turnstile.timeout` | `3s` | How long to wait for Cloudflare, to connect and, separately, to answer; a call can take up to twice this | | `who.turnstile.fail-open` | `false` | Lets requests through when Cloudflare cannot be reached or answers an error. A token Cloudflare refuses always fails | | `who.passkey.rp-id` | none | The application's own host, such as `app.example.com`. Required with `who-passkey`: startup fails without it. Never use a registrable domain that other apps share | | `who.passkey.rp-name` | `who` | Name of the relying party, shown by authenticators. Must not be blank | | `who.passkey.allowed-origins` | `https://` | Origins a registration or sign-in response may come from: each a scheme (`http` or `https`), a host and an optional port, with no path, such as `http://localhost:8080`. Startup fails on anything else | | `who.oidc.success-url` | `/` | Where a provider sign-in lands. A path on this site | | `who.oidc.failure-url` | `/` | Where a pending sign-up lands, with `pending=sign-up`, and every failed provider sign-in, with `error=already-linked`, `signed-in` or `signin-failed`. A path on this site; list it in `who.security.public-paths` | | `who.oidc.link-url` | `success-url` | Where a link the signed-in person asked for lands: `pending=link` to confirm it, `error=already-linked`, or nothing for an account they already had. A path on this site, such as the account settings page | | `who.oidc.sign-up-window` | `10m` | How long a pending sign-up waits for the person to confirm it | | `who.oidc.providers..enabled` | `true` | Leaves one client registration out of sign-in when `false` | | `who.oidc.providers..issuer` | none | The issuer, for an OpenID Connect provider configured by endpoints, or an OAuth 2 provider | | `who.oidc.providers..subject-attribute` | none | The user-info attribute holding the account's immutable id, for an OAuth 2 provider other than github.com | | `who.oidc.providers..trust-email` | `true` for Google and github.com, else `false` | Whether a verified address from this provider reaches the sign-up policy | See [Email Links](https://jwcarman.github.io/who/guides/email-links/index.md), [Passkeys](https://jwcarman.github.io/who/guides/passkeys/index.md) and [Social Login](https://jwcarman.github.io/who/guides/social-login/index.md) for how these fit together. ## Endpoints Every who endpoint lives under `who.base-path`. With the default `/who`: | Endpoint | Module | What it does | | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | ----------------------------------------------------------------------------------- | | `GET /who/sign-in` | who-spring-security | Which sign-in methods are on, and the providers to draw buttons for. Public | | `POST /who/logout` | who-spring-security | Sign out | | `POST /who/email/send` | who-email-link | Email a sign-in link and code | | `POST /who/email/sign-in` | who-email-link | Sign in with the link's token, or the address and code | | `POST /who/passkey/sign-in/options`, `POST /who/passkey/sign-in` | who-passkey | Sign in with a passkey | | `GET /who/oidc/authorize/{registrationId}` | who-oidc | Start a provider sign-in | | `GET /who/oidc/callback/{registrationId}` | who-oidc | The provider's redirect URI | | `GET /who/oidc/pending`, `POST /who/oidc/pending/sign-up`, `POST /who/oidc/pending/link` | who-oidc | Confirm a pending sign-up or link | | `GET /who/me` | who-spring-security | The signed-in identity, its permissions, how it signed in and its credential counts | | `GET /who/me/sessions`, `DELETE /who/me/sessions/{id}`, `DELETE /who/me/sessions?others=true` | who-spring-security | See and end your sessions | | `GET /who/me/passkeys`, `DELETE /who/me/passkeys/{credentialId}` | who-passkey | List and remove your passkeys | | `POST /who/me/passkeys/options`, `POST /who/me/passkeys` | who-passkey | Register a passkey | | `GET /who/me/email-addresses`, `DELETE /who/me/email-addresses/{id}` | who-email-link | List and remove your email addresses | | `POST /who/me/email-addresses`, `POST /who/me/email-addresses/confirmations` | who-email-link | Add or change an email address | | `GET /who/me/accounts`, `DELETE /who/me/accounts/{id}` | who-oidc | List and unlink your provider accounts | | `POST /who/me/accounts/{registrationId}` | who-oidc | Start linking a provider account | | `GET /who/me/api-keys`, `POST /who/me/api-keys`, `POST /who/me/api-keys/{id}/rotations`, `DELETE /who/me/api-keys/{id}`, `GET /who/me/api-keys/current` | who-apikey | Manage your API keys | | `GET /who/identities`, `GET /who/identities/{id}`, `PATCH /who/identities/{id}` | who-admin | List, read, deactivate and reactivate identities | | `PUT /who/identities/{id}/roles/{role}`, `DELETE /who/identities/{id}/roles/{role}` | who-admin | Assign and remove roles | | `GET /who/roles` | who-admin | The roles that exist | | `POST /who/invitations` | who-admin, with who-email-link | Invite someone by email address | Everything under `/who/me` acts on the caller's own data only; see [Your Account](https://jwcarman.github.io/who/guides/account/index.md) for who may call each one. The admin endpoints need who's own permissions; see [Admin](https://jwcarman.github.io/who/guides/admin/index.md). ### who's controllers and your Spring MVC setup `/who/me` and everything under it, and the admin endpoints, are Spring MVC controllers. Your application's MVC setup reaches them as it reaches your own controllers: - **A path prefix or servlet path fails startup.** who's sign-in filters, logout, public paths and error handling sit at `who.base-path`, so a `configurePathMatch` prefix that matches who's controllers, a `spring.mvc.servlet.path` other than `/`, or a `WhoPaths` bean whose root is not `who.base-path` is refused at startup, naming the endpoints that moved. Exclude who's controllers from a prefix (match on your own package) or set `who.base-path` instead. - **A `ResponseBodyAdvice` changes who's answers.** One that wraps every body in an envelope wraps who's too, and who's client cannot read them. Limit it to your own packages (`@ControllerAdvice(basePackages = ...)`). who's errors are not affected: who writes them itself. - **who's JSON shape relies on Jackson 3.** Its answer types pin their names, nulls and instants with Jackson annotations, so `spring.jackson` settings do not change them. A Gson, JSON-B or Jackson 2 converter preferred over Spring's Jackson 3 one ignores those annotations. - **Your interceptors and filters run for who's endpoints** like any request. Your own endpoints may live under the same root; who's rules apply only to its own paths, so yours still need whatever sign-in your chain asks for. # Database Setup Who ships its own schema files on the classpath, one per module. The autoconfiguration runs them automatically — only modules present on the classpath contribute scripts, and all scripts use `CREATE TABLE IF NOT EXISTS` so they are safe to run on every startup. ## Auto-initialization By default, schemas run automatically when the datasource is an embedded database (H2, HSQLDB, Derby). Control this with: ``` who: initialize-schema: embedded # always | embedded | never (default: embedded) ``` PostgreSQL is not an embedded database, so with the default the scripts do not run. Set `who.initialize-schema: always` for local development, or manage the schema with Flyway or Liquibase. For production, set `who.initialize-schema: never` and use Flyway or Liquibase. The `who-rbac` schema requires the `who_identity` table from `who-jdbc` (`who_identity_role.identity_id` references it). Run the `who-jdbc` schema first. The passkey tables reference `who_identity` too. The Flyway and Liquibase copies below are already in that order. ## Transactions and locks Three rules hold under concurrent requests only because who counts and changes in one database transaction that holds row locks: the [last-credential rule](https://jwcarman.github.io/who/guides/account/#the-last-credential-rule) locks the identity's `who_identity` row, the [last-admin rule](https://jwcarman.github.io/who/guides/admin/#the-last-admin) locks `who_role` rows, and an [invitation](https://jwcarman.github.io/who/guides/admin/#invitations) creates everything in one transaction. They need: - **Exactly one `PlatformTransactionManager`**, which who uses for them. Spring Boot makes it for a single `DataSource`. With two or more, an application with `who-passkey`, `who-email-link`, `who-oidc` or `who-admin` fails startup; mark the one for who's `DataSource` `@Primary`. - **who's `JdbcClient` on that manager's `DataSource`.** The locks are taken through who's `JdbcClient`; if its `DataSource` is not the one the transaction manager manages, each statement runs in a connection of its own, the lock is released at once, and two concurrent removals can both pass. Spring Boot's `JdbcClient` and transaction manager share the single `DataSource`, so only an application that defines its own `JdbcClient`, `DataSource` or transaction manager needs to check this. - **`READ COMMITTED`.** The guards ask for it on their own transactions, whatever the database's default, so that a removal that waited for the lock counts what the first one committed. Run `LastCredentialGuard.removeIfNotLast` from your own code outside any transaction of yours: inside one, it joins your transaction at your transaction's isolation, and under `REPEATABLE READ` the count can be stale. The same holds for `LastAdminGuard`. ## Flyway Copy the following file to `src/main/resources/db/migration/V1__who.sql` in your application. If the application already has migrations, give the file the next free version number instead of `V1`: ``` CREATE TABLE IF NOT EXISTS who_identity ( id UUID PRIMARY KEY, status VARCHAR(20) NOT NULL, created_at TIMESTAMP WITH TIME ZONE NOT NULL, updated_at TIMESTAMP WITH TIME ZONE NOT NULL ); CREATE TABLE IF NOT EXISTS who_credential_identity ( credential_id UUID PRIMARY KEY, identity_id UUID NOT NULL, FOREIGN KEY (identity_id) REFERENCES who_identity(id) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS who_session ( id UUID PRIMARY KEY, identity_id UUID NOT NULL, credential_id UUID NOT NULL, sign_in_method VARCHAR(30) NOT NULL, signed_in_at TIMESTAMP WITH TIME ZONE NOT NULL, last_seen_at TIMESTAMP WITH TIME ZONE NOT NULL, user_agent VARCHAR(512), ended_at TIMESTAMP WITH TIME ZONE, FOREIGN KEY (identity_id) REFERENCES who_identity(id) ON DELETE CASCADE ); CREATE INDEX IF NOT EXISTS who_session_identity_idx ON who_session (identity_id); CREATE INDEX IF NOT EXISTS who_session_last_seen_idx ON who_session (last_seen_at); CREATE INDEX IF NOT EXISTS who_session_ended_idx ON who_session (ended_at); CREATE TABLE IF NOT EXISTS who_role ( id UUID PRIMARY KEY, name VARCHAR(255) NOT NULL UNIQUE ); CREATE TABLE IF NOT EXISTS who_role_permission ( role_id UUID NOT NULL, permission VARCHAR(255) NOT NULL, PRIMARY KEY (role_id, permission), FOREIGN KEY (role_id) REFERENCES who_role(id) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS who_identity_role ( identity_id UUID NOT NULL, role_id UUID NOT NULL, PRIMARY KEY (identity_id, role_id), FOREIGN KEY (identity_id) REFERENCES who_identity(id) ON DELETE CASCADE, FOREIGN KEY (role_id) REFERENCES who_role(id) ON DELETE CASCADE ); ALTER TABLE IF EXISTS who_jwt_credential RENAME TO who_federated_credential; CREATE TABLE IF NOT EXISTS who_federated_credential ( id UUID PRIMARY KEY, issuer VARCHAR(255) NOT NULL, subject VARCHAR(255) NOT NULL, UNIQUE (issuer, subject) ); CREATE TABLE IF NOT EXISTS who_enrollment_token ( id UUID PRIMARY KEY, identity_id UUID NOT NULL, token_value VARCHAR(255) NOT NULL UNIQUE, status VARCHAR(20) NOT NULL, created_at TIMESTAMP WITH TIME ZONE NOT NULL, expires_at TIMESTAMP WITH TIME ZONE NOT NULL, redeemed_at TIMESTAMP WITH TIME ZONE, FOREIGN KEY (identity_id) REFERENCES who_identity(id) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS who_api_key_credential ( id UUID PRIMARY KEY, name VARCHAR(255) NOT NULL, key_hash VARCHAR(64) NOT NULL UNIQUE, created_at TIMESTAMP WITH TIME ZONE NOT NULL, expires_at TIMESTAMP WITH TIME ZONE NOT NULL, last_used_at TIMESTAMP WITH TIME ZONE ); CREATE TABLE IF NOT EXISTS who_api_key_scope ( credential_id UUID NOT NULL REFERENCES who_api_key_credential (id) ON DELETE CASCADE, permission VARCHAR(255) NOT NULL, PRIMARY KEY (credential_id, permission) ); CREATE TABLE IF NOT EXISTS who_email_credential ( id UUID PRIMARY KEY, address VARCHAR(320) NOT NULL UNIQUE ); CREATE TABLE IF NOT EXISTS who_email_link_token ( credential_id UUID PRIMARY KEY REFERENCES who_email_credential (id) ON DELETE CASCADE, token_hash VARCHAR(64) NOT NULL UNIQUE, created_at TIMESTAMP WITH TIME ZONE NOT NULL, expires_at TIMESTAMP WITH TIME ZONE NOT NULL, code_hash VARCHAR(64) NOT NULL, code_attempts INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS who_email_address_request ( id UUID PRIMARY KEY, identity_id UUID NOT NULL UNIQUE REFERENCES who_identity (id) ON DELETE CASCADE, address VARCHAR(320) NOT NULL, replaces_credential_id UUID, token_hash VARCHAR(64) NOT NULL UNIQUE, code_hash VARCHAR(64) NOT NULL, code_attempts INTEGER NOT NULL, created_at TIMESTAMP WITH TIME ZONE NOT NULL, expires_at TIMESTAMP WITH TIME ZONE NOT NULL ); CREATE INDEX IF NOT EXISTS ix_who_email_address_request_address ON who_email_address_request (address); CREATE TABLE IF NOT EXISTS who_passkey_user ( id VARCHAR(1000) PRIMARY KEY, identity_id UUID NOT NULL UNIQUE REFERENCES who_identity (id) ON DELETE CASCADE, name VARCHAR(320) NOT NULL, display_name VARCHAR(320) ); CREATE TABLE IF NOT EXISTS who_passkey_credential ( credential_id VARCHAR(1000) PRIMARY KEY, user_entity_user_id VARCHAR(1000) NOT NULL REFERENCES who_passkey_user (id) ON DELETE CASCADE, public_key BYTEA NOT NULL, signature_count BIGINT, uv_initialized BOOLEAN, backup_eligible BOOLEAN NOT NULL, authenticator_transports VARCHAR(1000), public_key_credential_type VARCHAR(100), backup_state BOOLEAN NOT NULL, attestation_object BYTEA, attestation_client_data_json BYTEA, created TIMESTAMP WITH TIME ZONE NOT NULL, last_used TIMESTAMP WITH TIME ZONE, label VARCHAR(1000) NOT NULL, credential_uuid UUID NOT NULL UNIQUE ); ``` ## Passkey storage is PostgreSQL only The `who-passkey` repositories use `ON CONFLICT`, so passkey storage works on PostgreSQL 14+ only. The other modules also run on H2. The tables are used only when `who-passkey` is on the classpath. See [Passkeys](https://jwcarman.github.io/who/guides/passkeys/index.md). ## Liquibase Every module ships a changelog that matches its bundled `who--schema.sql`. `who-autoconfigure` ships `org/jwcarman/who/db/who-changelog.xml`, which includes the changelog of each module on the classpath, `who-jdbc` first. Include that one file from your master changelog: ``` databaseChangeLog: - include: file: classpath:org/jwcarman/who/db/who-changelog.xml ``` Then set `who.initialize-schema: never`. Modules that are not on the classpath are skipped. The `classpath:` includes inside `who-changelog.xml` need Spring Boot's Liquibase integration. The Liquibase CLI and the Liquibase Maven plugin may skip them without a warning, so run the changelog through Spring Boot. The changelogs have no preconditions, except the one that renames `who_jwt_credential` to `who_federated_credential` and runs only when the old table exists. Use them on a fresh schema. If the tables already exist because the bundled schema files created them, run Liquibase `changelog-sync` once before the first update, so Liquibase records the change sets as applied and does not try to create the tables again. # Signing in # Email Links Who supports sign-in by an emailed link or code, in the `who-email-link` module. The user enters an address and gets an email with a link and a short code. Opening the link, or typing the code, signs them in and starts an HTTP session. It is built on Spring Security's one-time-token login. Who supplies the hooks and keeps Spring's endpoints: `POST /who/email/send`, `POST /who/email/sign-in` and `POST /who/logout`. Who adds one endpoint of its own, `GET /who/me`. Add `who-email-link` to turn email links on; an application without the jar has none of this. ## Turn it on Add the dependency (its version comes from who's BOM): ``` org.jwcarman.who who-email-link ``` Then set the page of your app that receives sign-in links, and the code secret: ``` who: email-link: link-base-url: https://app.example.com/signin code-secret: ``` It also needs a way to send its emails: add `who-email` and `who-email-smtp`, and set `spring.mail.host` and `who.email.from`: ``` spring: mail: host: smtp.example.com who: email: from: no-reply@example.com email-link: link-base-url: https://app.example.com/signin code-secret: ``` [Email](https://jwcarman.github.io/who/guides/email/index.md) covers changing what the emails say, HTML, subjects and languages, and sending through something other than SMTP. Startup fails, and the message names the fix, if: - `link-base-url` is missing or blank; - `who.email-link.code-length` is below 6; - `who.email-link.code-max-attempts` is below 1; - `who.email-link.code-secret` is missing, shorter than 32 characters, or an unresolved placeholder such as `${CODE_SECRET}` (Spring binds an unset variable as that literal text); - there is no way to send its emails: no `who-email` (or `WhoEmailRenderer` of your own), or no `who-email-smtp` with `spring.mail.host` (or `WhoEmailSender` of your own); - `who.email-link.resend-interval` is longer than `who.email-link.token-ttl`. Each message also says how to turn email links off without removing the jar: `who.email-link.enabled=false`. who sends four emails from here, each rendered from a template you can replace: `sign-in`, `invitation`, `address-confirmation` and `address-changed`. The sign-in email carries the link, the code in groups (such as `K7F-2QM`, easier to read and type) and how long both stay valid. The link is `link-base-url` followed by `#token=` and the token. [Email](https://jwcarman.github.io/who/guides/email/#what-each-email-carries) lists what each one carries. See the [Configuration Reference](https://jwcarman.github.io/who/guides/configuration/index.md) for all the properties. ## Code secret `who.email-link.code-secret` is required. It must be at least 32 characters, and every instance of your application must use the same value. Who stores the code only as an HMAC keyed with this secret. The secret is never stored in the database, so a copy of the database does not let anyone work out or check codes offline. Keep it in your secret store, not in source control. Generate it with `openssl rand -base64 32`, and do not reuse another secret, such as a JWT signing key or a database password. Like any secret property, it shows in `/actuator/env` and `/actuator/configprops` if those endpoints have `show-values` enabled. If you change the secret, codes already sent stop working. The links in those emails still work. ## Wire the chain With no `SecurityFilterChain` of your own there is nothing to wire: who's default chain mounts email links, opens `/who/email/send` and `/who/email/sign-in` to signed-out requests, and does everything listed below (see [Getting Started](https://jwcarman.github.io/who/guides/getting-started/#secure-the-app)). Open the page `link-base-url` points at, and the assets it loads, yourself: ``` who: security: public-paths: - /signin - /assets/** ``` ### Your own chain In a chain of your own, `WhoSecurity.all()` mounts every sign-in method at once (see [Getting Started](https://jwcarman.github.io/who/guides/getting-started/#your-own-chain)). To mount the browser methods only, apply `WhoWebSecurity.passwordless()` to the `SecurityFilterChain` that serves your browser app: ``` @Bean SecurityFilterChain browserChain(HttpSecurity http) throws Exception { http.with(WhoWebSecurity.passwordless(), Customizer.withDefaults()); http.authorizeHttpRequests(a -> a .requestMatchers("/who/email/send", "/who/email/sign-in", "/signin").permitAll() .anyRequest().authenticated()); return http.build(); } ``` `passwordless()` configures Spring's one-time-token login itself. Do not also call `oneTimeTokenLogin()` on the chain. Who's hooks are beans, so a second `oneTimeTokenLogin()` in the same app would pick them up too. It also: - turns on CSRF protection with Spring's `csrf.spa()`; - hands unauthenticated requests to your application as a `NotSignedInException` (`401` unless you map it; see [Errors](https://jwcarman.github.io/who/guides/errors/index.md)), with no redirect; - makes `/who/logout` answer `204` and clear the `XSRF-TOKEN` cookie; - changes the session id at sign-in; - adds `Referrer-Policy: no-referrer`. Startup fails if the chain disables CSRF or is `STATELESS`. A session in a chain without CSRF protection lets other sites forge requests. Do not combine `passwordless()` with a stateless chain. Who detects `sessionCreationPolicy(STATELESS)`, but not a stateless chain that also sets its own `SecurityContextRepository`. `WhoSecurity.all()` serves API keys and JWTs in the same chain, statelessly and without CSRF for the requests that carry them. With `passwordless()` alone, keep stateless `/api/**` callers in a separate chain: ``` @Bean @Order(1) SecurityFilterChain apiChain(HttpSecurity http) throws Exception { http.securityMatcher("/api/**") .with(WhoApiKeySecurity.apiKey(), Customizer.withDefaults()) .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(a -> a.anyRequest().authenticated()); return http.build(); } ``` The session holds only the identity id and the credential id. On every request who loads the identity and its permissions again. If the identity is no longer active, or the credential is no longer linked to it, the session is invalidated and the request gets `401`. Role and permission changes apply on the next request. To keep sessions in your database, see [Sessions](https://jwcarman.github.io/who/guides/sessions/index.md). A denied request is not saved: `passwordless()` uses a `NullRequestCache`, so there is no redirect to the original request after sign-in. ## The sign-in flow The [TypeScript client](https://jwcarman.github.io/who/guides/client/#email-links) makes these calls for you, CSRF included: `who.email.send`, `who.email.signIn` and `who.email.signInFromLocation`. All requests are JSON. Every POST needs the CSRF token. Spring sets an `XSRF-TOKEN` cookie that the page can read. The page sends its raw value in the `X-XSRF-TOKEN` header on every POST, including `/who/email/send`, `/who/email/sign-in` and `/who/logout`. ``` function xsrf() { return document.cookie.split('; ') .find(c => c.startsWith('XSRF-TOKEN='))?.split('=')[1]; } async function post(path, body) { return fetch(path, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-XSRF-TOKEN': decodeURIComponent(xsrf() ?? '') }, body: body === undefined ? undefined : JSON.stringify(body) }); } ``` The cookie exists after the first response from the server, so make any GET first (for example `GET /who/me`, which answers `401` but sets the cookie). `/who/logout` clears the cookie. After signing out, make another GET before the next POST, or `/who/email/send` answers `403`. 1. **Ask for a link and code.** `POST /who/email/send` with `{"email": "user@example.com"}`. The answer is always `202` with an empty body, whether or not the address is registered. The server does the lookup and sends the email after it has answered. ``` await post('/who/email/send', { email }); ``` The email carries the link and a code. The code uses the Crockford base32 alphabet (`0-9` and `A-Z` without `I`, `L`, `O` and `U`), has `who.email-link.code-length` characters (default 6), and is shown in groups, such as `K7F-2QM`. The user can use either one. 1. **The user opens the link.** The browser loads your `/signin` page. The token is in the URL fragment, so it is never sent to a server. A mail scanner that fetches the link does nothing. 1. **Confirm.** The page reads the token from `location.hash` and posts it. Remove it from the address bar afterwards. ``` const token = new URLSearchParams(location.hash.slice(1)).get('token'); history.replaceState(null, '', location.pathname); const res = await post('/who/email/sign-in', { token }); if (res.ok) { const { identityId } = await res.json(); } ``` On success the answer is `200` with `{"identityId": "..."}` and a session cookie. Every failure is a `SignInFailedException` (`401` unless your application maps it otherwise; see [Errors](https://jwcarman.github.io/who/guides/errors/index.md)): an unknown, used or expired token, a wrong, burnt or expired code, an identity that is not active, or a malformed body. **Or type the code.** A user who cannot open the link in this browser (the mail app opened it elsewhere, or a mail scanner used it up) types the code from the email instead. The page posts the address and the code to the same endpoint: ``` const res = await post('/who/email/sign-in', { email, code }); ``` The body is either `{"token": "..."}` or `{"email": "...", "code": "..."}`. A body with both, or with neither, fails. Using the link ends the code, and using the code ends the link. The code is not tied to the browser that asked for it, so a user can ask on a laptop and type the code on a phone. 1. **Use the session.** `GET /who/me` answers `{"identityId": "...", "permissions": ["..."]}` for a signed-in caller and throws `NotSignedInException` otherwise (`401`, in your application's error format). 1. **Sign out.** `POST /who/logout` answers `204` and clears the `XSRF-TOKEN` cookie. Fetch the cookie again with any GET (for example `GET /who/me`) before the next POST. ``` await post('/who/logout'); await fetch('/who/me', { credentials: 'same-origin' }); // sets a new XSRF-TOKEN cookie ``` Each address holds one live link and code. A new request replaces both, so only the newest email works. A link or code works once. ### How the code is read Input is case-insensitive. Spaces and dashes are ignored, so `k7f 2qm` and `K7F-2QM` are the same code. `O` is read as `0`, and `I` and `L` are read as `1`, so a mistyped look-alike still works. ### The attempt limit A code is short, so it has an attempt limit. After `who.email-link.code-max-attempts` wrong codes (default 5) for an address, its code is burnt: even the right code fails. The link in the same email still works until it expires. A new request, once the [resend interval](#the-resend-interval) has passed, issues a fresh code with a fresh count. A burnt code, a wrong code, an unknown address and an expired code all fail the same way, so the response tells an attacker nothing. ### How strong is the code With the defaults, a code is one of 32^6 ≈ 1.07 billion values, and each code allows 5 guesses. An attacker can have a fresh code issued once per [resend interval](#the-resend-interval) (60 seconds by default), so about 7,200 guesses a day against one address. That is about a 1-in-150,000 chance per day of taking over one targeted address, while the victim receives about 1,440 emails. Spraying many known addresses scales linearly: across 100,000 addresses, with no limit at the ingress, that is about 0.7 expected takeovers a day. So: - per-IP rate limits at the ingress are required (see [Rate limiting at the ingress](#rate-limiting-at-the-ingress)); - for large user bases, set `who.email-link.code-length: 8` (about 1 trillion codes, 1024 times harder); - alert on volumes of failed sign-ins. Also, don't run `/who/email/sign-in` inside a transaction: the attempt count must commit even when the sign-in fails, or the attempt limit stops working. And limit the request body size at the ingress. ## Registering addresses Only registered addresses can sign in. Register an address for an existing identity: ``` Identity identity = whoService.createIdentity(); emailCredentialService.register(identity, "user@example.com"); ``` Call `register` only with an address you vouch for, for example one you are sending an invitation to. Who does not verify ownership here. For a person adding an address to their own identity, use the [confirmed flow](#adding-or-changing-an-address) instead. `register` throws `EmailAddressTakenException` if the address is registered to another identity. If the address is already the identity's own, `register` returns that credential. If it is registered but linked to no identity (its identity was deleted directly, not with [`WhoService.deleteIdentity`](https://jwcarman.github.io/who/guides/getting-started/#deleting-an-identity)), `register` deletes that old credential, along with any sign-in link sent before, and registers a new one for the identity. Addresses are trimmed and lower-cased. `EmailCredentialService` also has `findByAddress(String)` and `revoke(UUID credentialId)`. `revoke` deletes the credential and its link to the identity. ## Adding or changing an address A signed-in person can add an address to their identity, or make an address theirs in place of one they have, by confirming a link or code sent to it. Until they confirm, nothing changes: an address is never attached without proof that the person reads its mailbox. Otherwise anyone could claim another person's address, which would then be taken, or get someone to sign in to an identity that is not theirs. Both endpoints need a browser session for the signed-in identity, signed in within `who.security.recent-sign-in` (10 minutes by default), and a CSRF token like every POST. Signed out is `401` (`NotSignedInException`); an older sign-in is `401` (`ReauthenticationRequiredException`): sign the person in again and retry. An API key or a bearer token, even beside the session cookie, is `403`. The [TypeScript client](https://jwcarman.github.io/who/guides/client/#your-account) has these calls under `who.me.emailAddresses`: `list`, `add`, `confirm`, `confirmFromLocation` and `remove`. Ask for an address: ``` await post('/who/me/email-addresses', { address: 'new@example.com' }); // 202 await post('/who/me/email-addresses', { address: 'new@example.com', replaces: '' }); // 202, a change ``` The answer is `202` whatever becomes of the request, and the rest runs on the email thread, as sign-in does, so the endpoint does not tell whether an address is taken. who sends the address a link and a code unless: - the text is not an address; - the address is registered already, to anyone, the caller included; - the identity asked within `who.email-link.resend-interval`, for any address, or anyone asked for this address within it. A new request replaces the identity's earlier one. Each is published as `EmailAddressConfirmationRequested` with its outcome. `replaces` must be the id of one of the caller's own addresses, as `GET /who/me/email-addresses` lists them, or the answer is `404` (`EmailCredentialNotFoundException`). The link is `who.email-link.address-confirmation-url` (default `link-base-url`) followed by `#confirm-address=` and the token. The page reads the token from the fragment and posts it, while signed in: ``` await post('/who/me/email-addresses/confirmations', { token }); // { "credentialId": "..." } await post('/who/me/email-addresses/confirmations', { code: 'K7F-2QM' }); // or the typed code ``` Only the identity that asked can confirm: the same token or code does nothing for anyone else signed in. A code counts against `who.email-link.code-max-attempts`, as at sign-in. A link or code works once and lasts `who.email-link.token-ttl`. No match is `400` (`InvalidEmailAddressConfirmationException`), and an address someone registered in the meantime is `409` (`EmailAddressTakenException`). On confirmation who adds the address and publishes `CredentialAdded`. For a change, it adds the new address and revokes the old one in one transaction (`CredentialAdded`, then `CredentialRevoked`), and then emails the old address that it was replaced, showing the new one masked (`n***@example.com`). The old address is the one most likely to still belong to the real owner if someone else had their session, so it always hears about it. A failure to send that notice is logged and does not undo the change. Revoking the old address ends every session signed in with it, as any revoked credential does, including the one that made the change if it signed in with that address: the person signs in again with the new one. To remove an address without replacing it, the person calls `DELETE /who/me/email-addresses/{id}` (see [Your Account](https://jwcarman.github.io/who/guides/account/#email-addresses)): a browser session signed in recently, `204`, or `409` (`last-credential`) when it is their last way to sign in. From your own code, `EmailCredentialService.revoke` checks neither ownership nor that rule; run it through `LastCredentialGuard` (see [the last-credential rule](https://jwcarman.github.io/who/guides/account/#the-last-credential-rule)). `EmailAddressChanges` is the bean behind the endpoints, if you want the same flow under your own URLs. ## Sending a link from your own code `POST /who/email/send` answers `202` at once and does the work in the background. To invite someone, use [`InvitationService`](https://jwcarman.github.io/who/guides/admin/#invitationservice), which creates the identity and sends the link in the right order. To send a link yourself, call `EmailLinkIssuer.issue(address, tokenValue)`. The `EmailLinkIssuer` is a bean. `tokenValue` is a random, URL-safe value that you generate. Who generates the code itself. `issue` returns an `EmailLinkOutcome`: | Outcome | Meaning | | ------------------- | ------------------------------------------------------------------------------------------ | | `SENT` | The link and code were stored and their email sent through `WhoEmails`. | | `UNKNOWN_ADDRESS` | The text is not an address, or no email credential has it. | | `INACTIVE_IDENTITY` | The address is known, but its identity is not active. | | `RESEND_SUPPRESSED` | A link was sent within the [resend interval](#the-resend-interval). | | `SEND_FAILED` | A step failed. The failure is logged, and a token already stored for that send is removed. | `issue` never throws. The `/who/email/send` endpoint ignores the outcome, so it still reveals nothing about an address. Show the outcome only to a caller you trust, such as the owner who sent an invitation. `issue` is synchronous and uses its own transactions. If you call it while a transaction of yours is open, call it after that transaction commits, with a new transaction of its own. Otherwise the send happens before your data is committed, and a failure in your transaction cannot take back the email: ``` TransactionTemplate afterCommit = new TransactionTemplate(transactionManager); afterCommit.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronization() { @Override public void afterCommit() { afterCommit.executeWithoutResult( status -> linkIssuer.issue(address, tokenValue)); } }); ``` The new transaction is needed because the finished transaction's connection is still bound while `afterCommit` runs, so the issuer's writes would not be committed. ## The resend interval Who sends at most one email per address per `who.email-link.resend-interval` (default 60 seconds). A request inside that window still answers `202`, but no email goes out. This protects a person's inbox from email bombing. The worst an attacker can do to a victim is delay their sign-in email by one interval. The link and the code expire together, after `who.email-link.token-ttl` (default 5 minutes). The resend interval must not be longer than that. ## Tracing the send `/who/email/send` answers `202` at once and sends the email on a virtual thread from the `whoEmailLinkExecutor` bean. That executor applies your `TaskDecorator` beans, as Spring Boot does to its own executors, so the send can stay in the request's trace and logging context. With Micrometer Tracing, register Spring's decorator: ``` @Bean TaskDecorator contextPropagatingTaskDecorator() { return new ContextPropagatingTaskDecorator(); } ``` To use your own executor instead, define a bean named `whoEmailLinkExecutor`. ## Human check Anyone can call `/who/email/send` and `/who/email/sign-in` while signed out. A script can make your app email your users over and over, or guess codes across many addresses. A human check, such as Cloudflare Turnstile, makes that expensive. who runs one in front of both endpoints whenever your application has a `WhoHumanCheck` bean; with none, it checks nothing. ### Cloudflare Turnstile Add `who-turnstile` (its version comes from who's BOM). Its jar turns the check on, and it needs the widget's secret key: ``` org.jwcarman.who who-turnstile ``` ``` who: turnstile: secret-key: ${TURNSTILE_SECRET} # required: startup fails without it hostnames: app.example.com # optional: a token made on another hostname fails timeout: 3s # optional fail-open: false # optional ``` The startup line then ends `human check: turnstile`. Turn the check off with `who.turnstile.enabled=false`. Your page runs Turnstile's widget, with its site key, and gets a fresh token for each request. Give the widget the endpoint's action, `email-send` or `email-sign-in`: who refuses a token made for any other action, so a token from elsewhere on your site cannot be spent here. Send the token in the `Who-Human-Check` header. With the [TypeScript client](https://jwcarman.github.io/who/guides/client/#email-links): ``` const token = await turnstileToken('email-send'); // your page's widget const sent = await who.email.send(email, { humanCheck: token }); if (!sent.ok) { // sent.reason === 'human-check-failed': show the widget again and retry } ``` Turnstile also guards the page your sign-in links open, since it posts the link's token to `/who/email/sign-in`. That page needs the widget and an `email-sign-in` token too. The [web-app example](https://github.com/jwcarman/who/tree/main/who-examples/web-app) does all of this. A request with no token, a token Cloudflare refuses, a wrong action or a hostname not listed fails with `HumanCheckFailedException`: `403`, `Who-Error: human-check-failed`. The endpoint never runs, so no email is sent and no code is tried. When Cloudflare cannot be reached in time or answers an error, the request fails too, unless `fail-open: true`; with it, those requests go through, but a token Cloudflare refuses still fails. In your own tests, point `who.turnstile.verify-url` at a stand-in for Cloudflare, such as WireMock, that answers like siteverify: `{"success": true, "action": "email-send", "hostname": "app.example.com"}`. Cloudflare's [test keys](https://developers.cloudflare.com/turnstile/troubleshooting/testing/) work for trying the check locally. Their answers carry no action and always the hostname `example.com`, so with one of the three test secret keys who passes a request on Cloudflare's success alone, and warns at startup. The always-fail (`2x…`) and already-spent (`3x…`) keys exercise your page's refusal path. A test key never accepts a real token, so never use one in production. ### Your own verifier `TurnstileHumanCheck` asks Cloudflare and hands the answer to a `TurnstileVerifier`, which decides. A `TurnstileVerifier` bean replaces who's. To add a rule of your own, start from `TurnstileVerifier.strict` so the action and hostname checks stay: ``` @Bean TurnstileVerifier turnstileVerifier(WhoProperties properties) { TurnstileVerifier strict = TurnstileVerifier.strict(properties.getTurnstile().getHostnames()); return (answer, request) -> strict.accepts(answer, request) && yourOwnRule(answer, request); } ``` `TurnstileAnswer` carries everything a rule needs from Cloudflare's answer: `success`, `action`, `hostname`, `challengeTs` (when the challenge was solved), `cdata` (the data your page gave the widget) and `errorCodes`. For example, to refuse tokens solved more than a minute ago: ``` return (answer, request) -> strict.accepts(answer, request) && answer.challengeTs().filter(solved -> solved.isAfter(Instant.now().minusSeconds(60))).isPresent(); ``` Your verifier is used even with a test key. ### The HTTP client who calls Cloudflare with a `RestClient` of its own, built from your application's HTTP client settings: `spring.http.clients.*`, or your own `HttpClientSettings` and `ClientHttpRequestFactoryBuilder` beans. The client library, SSL bundle, redirects and the rest carry over (`who-turnstile` brings `spring-boot-http-client` for them). Only the timeouts are replaced, by `who.turnstile.timeout`, so a slow Cloudflare can never hold a sign-in longer than who allows. With an `ObservationRegistry`, as Actuator provides, each call is observed as `http.client.requests`. who never uses your application's `RestClient.Builder`: its default headers and interceptors are meant for your own services, and must not travel to Cloudflare beside the secret, or log the form that carries it. `who.turnstile.hostnames` takes bare hostnames such as `app.example.com`; a scheme, port or path fails startup, since Cloudflare reports the hostname alone. The timeout bounds connecting and reading separately, so a call that connects slowly and then answers slowly can take up to twice `who.turnstile.timeout`. ### Behind a proxy who sends Cloudflare the client's address as the servlet container reports it. Behind a load balancer, set `server.forward-headers-strategy` so that address is the client's, not the proxy's. ### Your own check Any other vendor plugs in as a bean, and it replaces Turnstile's: ``` @Bean WhoHumanCheck humanCheck(MyVendorClient vendor) { return request -> request.token() .map(token -> vendor.verify(token, request.clientIp(), request.action())) .orElse(false); } ``` `HumanCheckRequest` holds the `Who-Human-Check` header (empty when the page sent none), the client's address and the action. who reads the request itself, so a check never sees the body. A check that throws refuses the request. In tests, `WhoHumanCheck.ALLOW_ALL` turns the check on and lets everyone through. ### Your own endpoints who checks only its own endpoints. To guard one of yours, such as a contact form, inject the `WhoHumanCheck` bean and ask it, with an action of your own: ``` @RestController class ContactController { private final ObjectProvider humanCheck; ContactController(ObjectProvider humanCheck) { this.humanCheck = humanCheck; } @PostMapping("/contact") void contact( @RequestBody ContactMessage message, @RequestHeader(name = WhoHumanCheck.HEADER, required = false) String token, HttpServletRequest request) { WhoHumanCheck check = humanCheck.getIfAvailable(); if (check != null && !check.passes( new HumanCheckRequest( Optional.ofNullable(token).filter(t -> !t.isBlank()), request.getRemoteAddr(), "contact"))) { throw new HumanCheckFailedException(); } // handle the message } @ExceptionHandler ResponseEntity refused(HumanCheckFailedException e) { return ResponseEntity.status(HttpStatus.FORBIDDEN) .header(WhoExceptionHandoff.HEADER, e.errorCode()) .build(); } } ``` - **The action is yours to name.** Give the widget the same one (`turnstile.render(..., { action: 'contact' })`): Turnstile's check refuses a token made for another action. Actions are up to 32 characters of letters, digits, `-` and `_`. - **No check bean, no check.** `ObjectProvider` lets the endpoint work when no check is configured, as who's do. Make the bean required instead if the endpoint must never go unchecked. - **The handler is optional.** Without it, Spring answers `403` from the exception's `@ResponseStatus`, and who's autoconfiguration still adds `Who-Error: human-check-failed`, which the TypeScript client reads; write one to give the body your own shape. - **CSRF still comes first:** the controller runs after the security chain. - **Checks you call yourself publish no event and count in no meter.** `HumanCheckPerformed` and `who.human-checks` cover who's endpoints. ## Rate limiting at the ingress The attempt limit is per address, not per client. Who does not limit requests by client IP and never reads `X-Forwarded-For`. Put per-IP limits on `/who/email/send` and `/who/email/sign-in` at the load balancer, WAF or ingress, where the real client address is known. With [Passkeys](https://jwcarman.github.io/who/guides/passkeys/index.md) on, limit `/who/passkey/sign-in/options` and `/who/passkey/sign-in` the same way: the options endpoint creates a session for any anonymous caller. For example, with nginx: ``` limit_req_zone $binary_remote_addr zone=who_signin:10m rate=10r/m; server { location = /who/email/send { limit_req zone=who_signin burst=5 nodelay; limit_req_status 429; proxy_pass http://app; } location = /who/email/sign-in { limit_req zone=who_signin burst=5 nodelay; limit_req_status 429; proxy_pass http://app; } } ``` Tune the rate to your users. Behind another proxy, make sure `$binary_remote_addr` is the client address (use the `realip` module). ## Session cookie Set the session cookie properties yourself. Who does not override them: ``` server: servlet: session: cookie: same-site: lax secure: true ``` `HttpOnly` is the Spring Boot default. Use `secure: false` only for local development over plain HTTP. ## Trust and recovery An email link signs in, so control of the mailbox is control of the identity. The mailbox is the root of trust. A user who loses the mailbox needs an administrator. Call `EmailCredentialService.revoke` for the old credential, then `register` with a new, verified address. Who has no admin tooling for this. ## One tenant per JVM Who assumes one tenant per JVM. Each customer application should have its own database. If one JVM serves several tenant databases, the token store and `WhoService` would need to be tenant-scoped. Who does not support that. ## Database The module adds `who_email_credential`, `who_email_link_token` and `who_email_address_request` (a pending address change, one per identity). Token and request rows hold the hash of the token and the HMAC of the code, never the values. See [Database Setup](https://jwcarman.github.io/who/guides/database/index.md). # Email who sends a few emails of its own: sign-in links and codes, invitations, address confirmations and the security notices that follow some changes. Every one of them goes through one class, `WhoEmails`, which does three things in order: 1. refuses if a database transaction is open; 1. renders the email, with a `WhoEmailRenderer`, into a subject, a text body and an optional HTML body; 1. hands the result, an `OutgoingEmail`, to a `WhoEmailSender`, which only delivers it. Rendering and delivery are separate modules, so you can change what the emails say without touching how they go out, and the reverse. | Module | What it does | | ---------------- | ---------------------------------------------------------------- | | `who-email` | Renders who's emails from Mustache templates you can override. | | `who-email-smtp` | Delivers them over SMTP, through Spring Boot's `JavaMailSender`. | ## Turn it on A module that sends email ([email links](https://jwcarman.github.io/who/guides/email-links/index.md), and the [passkey-added notice](https://jwcarman.github.io/who/guides/passkeys/#the-passkey-added-email)) needs both halves. Add them next to it (their versions come from who's BOM): ``` org.jwcarman.who who-email org.jwcarman.who who-email-smtp ``` and tell it where to send from: ``` spring: mail: host: smtp.example.com who: email: from: no-reply@example.com ``` `who-email-smtp` brings `spring-boot-starter-mail`. With it on the classpath and a mail host set, startup fails if `who.email.from` is missing. Email-link sign-in fails startup when there is no way to send its emails, and the message says which half is missing. The passkey-added notice is optional: without `WhoEmails` it is not sent, and who logs that once at startup. ## What who sends | Template | Module | Record | Sent when | | ---------------------- | ---------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `sign-in` | `who-email-link` | `EmailLinkMessage` | someone asks for a sign-in link | | `invitation` | `who-email-link` | `InvitationMessage` | an [invitation](https://jwcarman.github.io/who/guides/admin/#invitations) is made | | `address-confirmation` | `who-email-link` | `EmailAddressConfirmationMessage` | someone asks to [add or change an address](https://jwcarman.github.io/who/guides/email-links/#adding-or-changing-an-address) | | `address-changed` | `who-email-link` | `EmailAddressChangedMessage` | an address is replaced; it goes to the old one | | `passkey-added` | `who-passkey` | `PasskeyAddedMessage` | a passkey is added to an account | Each record implements `WhoEmail`: `address()` is the recipient, and `template()` names the template above. ## Templates who ships a plain-text template for every email, in its own words. To use yours, put a file with the template's name in `classpath:/templates/who/email/`. `who.email.templates` is a list of Spring resource locations, searched in order, to look elsewhere or in several places (a `file:` location lets you edit templates without a rebuild): ``` who.email.templates=classpath:/templates/who/email/,file:./email/ ``` Each location is one place, so use `classpath:`, not `classpath*:`: who looks a file up in each location in turn, and a `classpath*:` location never matches. | File | Effect | | -------------- | --------------------------------------------------------------------------------------------- | | `sign-in.txt` | replaces who's text for sign-in emails | | `sign-in.html` | adds an HTML body; the email becomes multipart, with who's text (or yours) as the alternative | A file you don't provide comes from who, so you can replace one email, or only add HTML to one. Templates are [Mustache](https://mustache.github.io/mustache.5.html), and every template is compiled at startup, so one that doesn't compile fails startup rather than the first send. A template sees three names: - `email`: the record, so `{{email.link}}` is `EmailLinkMessage.link()`; - `app`: your values from `who.email.model.*`, so `who.email.model.support-address` is `{{app.support-address}}`; - `extra`: values your `WhoEmailModelContributor` beans add for each email (below). A variable the model doesn't have fails the render: the email is not sent, and the feature reports it as not sent. A value that is present but null renders empty. `.html` templates escape what they insert; `.txt` templates do not, so a link's `&` stays as it is. For example, `src/main/resources/templates/who/email/sign-in.html`: ```

Hello from {{app.name}}.

Sign in, or enter {{email.formattedCode}}.

The link and the code expire in {{email.expiresIn}}.

{{> footer}} ``` `{{> footer}}` is a partial: `footer.html` from your location, or from who's if it had one. A partial in a `.txt` template is `footer.txt`. For each file, template or partial, who looks in this order, and the first that has it wins: 1. each location in `who.email.templates`, in order; 1. each library's location (below), in bean order; 1. who's own templates. ### What each email carries | Record | Accessors | | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `EmailLinkMessage` | `address`, `link`, `code`, `formattedCode` (such as `K7F-2QM`), `expiresAt`, `validFor`, `expiresIn` (such as `15 minutes`) | | `InvitationMessage` | the same, plus `roles`, the names of the roles the invitation gave | | `EmailAddressConfirmationMessage` | the same as `EmailLinkMessage`, plus `change`: true when the address replaces another (`{{#email.change}}…{{/email.change}}`) | | `EmailAddressChangedMessage` | `address` (the old address), `newAddress`, `maskedNewAddress` (such as `n***@example.com`) | | `PasskeyAddedMessage` | `address`, `label`, the passkey's name | Don't log a link or a code. ### Values of your own To give a template something who doesn't know, such as the person's display name, register a `WhoEmailModelContributor`: ``` @Bean WhoEmailModelContributor displayNames(Profiles profiles) { return email -> profiles.findByAddress(email.address()) .map(p -> Map.of("displayName", p.displayName())) .orElse(Map.of()); } ``` Templates then use `{{extra.displayName}}`. Every contributor's map is merged, and a later bean's key wins. Since a missing variable fails the render, give every email the keys your templates use. ### Templates from a library A library built on who can ship its own versions of who's emails, and its own subjects, by registering a `WhoEmailTemplatesContributor` bean, typically from its auto-configuration: ``` @Bean @Order(100) WhoEmailTemplatesContributor acmeEmailTemplates() { return new WhoEmailTemplatesContributor("classpath:/com/acme/email/", "com/acme/email-messages"); } ``` The first argument is the library's template location, searched after the application's and before who's. The second is the basename of a message bundle with the library's subjects, or `null`: subjects are read from the application's messages, then from each library's bundle, then from who's. Several libraries are searched in bean order (`@Order`). An application still replaces any one of a library's files from its own location, as it replaces who's. For a native image, the library registers its own with a `RuntimeHintsRegistrar`; who registers only its own. Register the templates as resources and the subjects as a resource bundle: ``` hints.resources().registerPattern("com/acme/email/*"); hints.resources().registerResourceBundle("com/acme/email-messages"); ``` ## Subjects A subject is the message `who.email.