Authentication
The Fleans REST API supports opt-in JWT bearer authentication via any OIDC-compliant identity provider (Keycloak, Auth0, Microsoft Entra ID, etc.). Authentication is disabled by default — when no Authentication:Authority is configured, the API runs fully unauthenticated, identical to previous behavior.
Why opt-in?
Section titled “Why opt-in?”Local development and single-tenant deployments often don’t need authentication. Production multi-tenant deployments do. By making it configuration-driven, the same binary serves both scenarios without recompilation.
Quick start
Section titled “Quick start”Add the Authentication section to your appsettings.json:
{ "Authentication": { "Authority": "https://your-idp.example.com/realms/fleans", "Audience": "fleans-api", "RequireHttpsMetadata": true }}Once Authority is set, all API endpoints (/Definitions/*, /Execution/*, /Instances/*, /UserTasks/*, /Deployments/*, /custom-tasks/*) and the gRPC external-task service that external workers connect to require a valid Authorization: Bearer <token> header. Requests without a token receive 401 Unauthorized. The token must also carry a Fleans role (admin, operator, user, deployer or debugger); without one every endpoint answers 403 Forbidden. See Authorization (roles).
Environment variable equivalent (for Docker Compose or container deployments):
Authentication__Authority=https://your-idp.example.com/realms/fleansAuthentication__Audience=fleans-apiAuthentication__RequireHttpsMetadata=falseConfiguration reference
Section titled “Configuration reference”| Key | Required | Default | Description |
|---|---|---|---|
Authority | Yes (to enable auth) | (absent — auth disabled) | OIDC issuer URL. When set, all API endpoints require a valid JWT. |
Audience | No | fleans-api (MCP server: fleans-mcp) | Expected aud claim in the JWT. |
RequireHttpsMetadata | No | true | Set to false only for local dev with an HTTP-only IdP (e.g., Keycloak dev mode). |
UserIdClaim | No | preferred_username | JWT claim holding the acting user id for user-task claim/complete. Its values must match what your BPMN camunda:assignee / camunda:candidateUsers contain. sub is also accepted. |
RoleClaim | No | roles | JWT claim holding the caller’s Fleans roles (admin, operator, user, deployer, debugger; one claim entry per role). Read by the API and the Admin UI. See Authorization (roles). |
GroupsClaim | No | groups | JWT claim holding the caller’s groups for candidateGroups checks and deploy reviewer groups (one claim entry per group). Also read by the Admin UI from the sign-in (ID token or UserInfo). Set it to roles to use roles instead. |
Behavior when enabled
Section titled “Behavior when enabled”- All API endpoints (
/Definitions/*,/Execution/*,/Instances/*,/UserTasks/*,/Deployments/*,/custom-tasks/*) and the gRPC external-task service require a validAuthorization: Bearer <token>header. Unauthenticated requests receive401 Unauthorized. A worker sends its token fromFleans__ExternalTaskWorker__AccessToken(orAccessTokenProvider); it needs theoperatorrole. - Each endpoint needs a role.
userreaches the tasklist,operatoralso runs and inspects instances,deployerdeploys,admindoes all of that and manages the cluster. A caller without the endpoint’s role receives403 Forbidden. The full table is in Authorization (roles). - The MCP server (
Fleans.Mcp) reads the sameAuthenticationkeys and enforces bearer tokens on its MCP endpoint with audiencefleans-mcp. The Aspire AppHost and the Helm chart pass oneAuthorityto the API, the MCP server and the admin UI. - Health endpoints (
/health,/alive) remain anonymous — they are exempt so that load balancers and orchestrators can probe without credentials. SeeFleans.ServiceDefaults/Extensions.csfor the implementation. - Swagger UI (
/swagger) is served only whenASPNETCORE_ENVIRONMENT=Development; the released images don’t set it, so they have no Swagger UI. - User-task identity comes from the token.
POST /UserTasks/{id}/claimand/completeact as the user in theUserIdClaimclaim (defaultpreferred_username). The bodyUserIdfield is optional. If you send it and it differs from the token, the request fails with403 Forbidden, so a caller can’t act as another user. Body-suppliedUserGroupsare ignored; groups come from theGroupsClaimclaim. A token without the user-id claim also gets403. This applies to releases after v0.5.0 (#793). v0.5.0 and earlier trust the bodyUserIdeven under JWT.
Authentication:Authority set, every API call carries a bearer token; user-task claims take candidate groups from the token's groups claim. Open interactive diagram ↗Identity providers
Section titled “Identity providers”Keycloak
Section titled “Keycloak”# 1. Start Keycloak dev instance on host port 8180# (8080 and 8081 are taken by the Quick Start bundle's admin UI and API)docker run -p 8180:8080 \ -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \ -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \ quay.io/keycloak/keycloak:latest start-dev
# 2. Create realm "fleans", client "fleans-api" with client credentials grant.# Create realm roles admin / operator / user, give the client's service account "admin",# and add a "User Realm Role" mapper with token claim name "roles" (multivalued).# See /fleans/reference/authorization/#identity-providers.
# 3. Configure Fleans# appsettings.json:# "Authentication": {# "Authority": "http://localhost:8180/realms/fleans",# "Audience": "fleans-api",# "RequireHttpsMetadata": false# }
# 4. Obtain a token and call the APITOKEN=$(curl -s -X POST http://localhost:8180/realms/fleans/protocol/openid-connect/token \ -d "grant_type=client_credentials" \ -d "client_id=fleans-api" \ -d "client_secret=YOUR_SECRET" | jq -r '.access_token')
curl -X POST http://localhost:8081/Definitions/deploy \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"BpmnXml":"..."}'Other OIDC providers
Section titled “Other OIDC providers”Configuration is identical — set Authority to your provider’s OIDC discovery URL and Audience to the configured client/API identifier. Provider-specific walkthroughs will be added as contributors submit them.
Client examples
Section titled “Client examples”# Obtain a token from your identity provider, then:TOKEN="<your-jwt-token>"
curl -X POST http://localhost:8081/Execution/start \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"WorkflowId":"my-process"}'.NET HttpClient
Section titled “.NET HttpClient”Use a DelegatingHandler to attach the bearer token automatically on every outgoing request:
public class BearerTokenHandler : DelegatingHandler{ private readonly ITokenProvider _tokenProvider;
public BearerTokenHandler(ITokenProvider tokenProvider) => _tokenProvider = tokenProvider;
protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { var token = await _tokenProvider.GetTokenAsync(cancellationToken); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); return await base.SendAsync(request, cancellationToken); }}
// Registration (e.g., in Program.cs):builder.Services.AddTransient<BearerTokenHandler>();builder.Services.AddHttpClient<IFleansClient, FleansClient>(client =>{ client.BaseAddress = new Uri("http://localhost:8081");}).AddHttpMessageHandler<BearerTokenHandler>();Management UI
Section titled “Management UI”The Fleans.Web Blazor admin UI supports the same opt-in pattern via OIDC Authorization Code flow with PKCE, persisting the resulting identity in a session cookie. Disabled by default — when no Authentication section is present, the UI runs unauthenticated, identical to today’s behaviour.
Why a different flow than the API?
Section titled “Why a different flow than the API?”Browser users don’t hold raw JWTs. The canonical pattern for server-side web apps is OIDC Authorization Code flow with PKCE, which exchanges the authorization code for tokens server-side and persists the identity in an encrypted session cookie. The API uses bearer JWTs because its callers are scripts and services that do hold tokens; the UI uses cookies because its callers are humans in browsers.
Config block (Management UI)
Section titled “Config block (Management UI)”{ "Authentication": { "Authority": "https://your-idp.example.com/realms/fleans", "ClientId": "fleans-web", "ClientSecret": "<from-IdP>", "RequireHttpsMetadata": true, "CookieExpireMinutes": 60, "KnownProxies": [], "KnownNetworks": [] }}Auth on iff both Authority AND ClientId are non-empty (single source of truth — same key namespace as the API). The shipped appsettings.json carries no Authentication block; a documented copy lives at src/Fleans/Fleans.Web/appsettings.example.jsonc and is not loaded at runtime.
| Key | Required | Default | Description |
|---|---|---|---|
Authority | Yes (to enable auth) | (absent — auth disabled) | OIDC issuer URL. |
ClientId | Yes (to enable auth) | (absent) | OAuth client id registered with the IdP. Must be a confidential client. |
ClientSecret | Yes when auth on | — | Confidential-client secret. Use dotnet user-secrets in dev; env var Authentication__ClientSecret (or a Secret/Key Vault binding) in prod. Never commit. |
RequireHttpsMetadata | No | true | Set to false only for local Keycloak dev mode (HTTP). |
CookieExpireMinutes | No | 60 | Sliding session cookie lifetime. Mirror the IdP’s access-token / management-page session lifetime so admin sessions in the UI and tokens used against the API don’t drift apart. |
KnownProxies | No | [] | Reverse-proxy IP addresses trusted to set X-Forwarded-For / X-Forwarded-Proto. Empty list = headers ignored. |
KnownNetworks | No | [] | Same as above but accepts CIDR ranges (e.g. 10.0.0.0/8). |
Environment variable equivalent (for Docker Compose or container deployments):
Authentication__Authority=https://your-idp.example.com/realms/fleansAuthentication__ClientId=fleans-webAuthentication__ClientSecret=... # source from a Secret/Key Vault binding in prod, not literalBehaviour when enabled
Section titled “Behaviour when enabled”- Every page is wrapped in
<AuthorizeRouteView>. Unauthenticated requests trigger an OIDC challenge → IdP login → callback to/signin-oidc→ session cookie issued → bounce to the originally-requested URL (deep links preserved). - Orleans Dashboard at
/dashboardis gated by an explicit middleware branch — Orleans’ dashboard middleware does not honour[Authorize], so the guard fires beforeMapOrleansDashboard. - NavMenu renders a
Signed in as <preferred_username>chip with aSign outbutton. The button submits an antiforgery-protected POST to/Account/Logoutthat clears both the cookie and the IdP session. /health,/alivestay anonymous (operator probes are unaffected)./Account/Login?returnUrl=…validatesreturnUrlagainst an inlineIsLocalUrlpredicate (same shape asIUrlHelper.IsLocalUrl). Open-redirect attacks (/\evil.com,//evil.com, absolute URLs, leading whitespace) collapse to/; well-formed local paths pass through.
Multi-instance deployments
Section titled “Multi-instance deployments”When Fleans.Web uses Redis for cluster membership (Fleans__Clustering__Provider unset or Redis, the default, as in the Compose bundle), it persists ASP.NET Data Protection keys to that orleans-redis connection, so cookies issued by replica A decrypt on replica B. With another clustering provider (for example Postgres), the Web host registers no Redis connection and keeps the keys in its own container: run a single fleans-web replica, and expect users to sign in again after it restarts.
Reverse proxies
Section titled “Reverse proxies”If Fleans.Web sits behind a reverse proxy or ingress that terminates TLS, populate KnownProxies (or KnownNetworks for CIDR ranges) so X-Forwarded-For / X-Forwarded-Proto are honoured when constructing OIDC redirect URIs. Empty defaults are deliberately strict — without an explicit allowlist the framework discards the headers, preventing host-spoofing from untrusted networks. Without it, the IdP sees an http:// redirect URI behind an HTTPS ingress and rejects the sign-in (redirect_uri_mismatch).
Both keys are lists. As environment variables, give each entry an index:
Authentication__KnownNetworks__0=10.0.0.0/8Authentication__KnownNetworks__1=172.16.0.0/12Authentication__KnownProxies__0=192.168.1.10On the Helm chart, set them under extraEnv (see Self-host with Helm). Use the address range your ingress controller’s pods run in. These keys are read only by Fleans.Web, and only when its authentication is on.
Local dev
Section titled “Local dev”A copy-paste Keycloak quickstart (Docker run, realm JSON, dotnet user-secrets commands, sample user) lives at tests/manual/30-web-auth/keycloak-dev.md. The full manual test plan (login round-trip, dashboard guard, open-redirect attack table, antiforgery on logout) is at tests/manual/30-web-auth/test-plan.md.
Pages need a role too: Settings needs only a sign-in, the operations pages need operator, the editor
needs deployer or admin, Custom Tasks and the environments board need admin, and the instance
page’s Debug mode needs debugger or admin. The side rail shows only the sections
the user may open, and a signed-in user without the page’s role sees Access denied rather than
another sign-in. The roles are read from the ID token or UserInfo through Authentication:RoleClaim.
See Authorization (roles).
Testing & troubleshooting
Section titled “Testing & troubleshooting”The manual regression test plans for authentication live at:
- API:
tests/manual/28-api-auth/test-plan.md— verifies the API works unauthenticated by default, returns401when auth is on and no token is provided, and accepts valid tokens. - Management UI:
tests/manual/30-web-auth/test-plan.md— verifies anonymous browse is allowed when noAuthenticationsection is present, every page (and/dashboard) returns 302 → IdP when auth is on, login round-trip preserves deep-link query strings, the open-redirect guard rejects every canonical attack input, and/Account/Logoutis antiforgery-protected.
Common errors:
| Symptom | Likely cause |
|---|---|
401 with no WWW-Authenticate response header | Authority URL is unreachable or the OIDC discovery endpoint returned an error at startup |
401 with invalid_token in WWW-Authenticate | Audience mismatch — the token’s aud claim doesn’t match the configured value |
401 on /health or /alive | Not expected — these endpoints are always anonymous; check for a reverse proxy stripping the path |
403 UserId does not match the authenticated user on claim/complete | The body UserId differs from the token’s UserIdClaim value. Omit UserId or send the token’s value |
403 on every endpoint with a valid token | The token has no Fleans role in Authentication:RoleClaim. See Authorization (roles) |
403 Authenticated user has no user id claim on claim/complete | The token lacks the UserIdClaim claim. Add a mapper in your IdP or point Authentication:UserIdClaim at a claim the token carries |
Related
Section titled “Related”- Authorization (roles) — the
admin/operator/user/deployer/debuggerroles and the role-to-endpoint and role-to-page tables.
See also
Section titled “See also”- Observability — health checks, metrics, logging, tracing, dashboards, alerting
- Deployment — how to wire
Authentication:Authority/Authentication:Audience(and the OIDC client id/secret for the admin UI) into Docker Compose, Kubernetes, and bare-VM deployments, including reverse-proxy +KnownProxiesnotes. - Helm Chart — Authentication — OIDC opt-in on the Helm chart.