# Authorizer Documentation > Authorizer is an open-source, self-hosted authentication and authorization server: OAuth2/OIDC, social login, MFA, passkeys, magic links, SAML/SCIM, OpenFGA fine-grained authorization, MCP server, and RFC 8693 agent delegation. Runs on 17 SQL, NoSQL and graph databases; configured entirely by CLI flags. This file contains all documentation content in a single document following the llmstxt.org standard. ## Introduction ### What is Authorizer? **Authorizer** is an open-source authentication and authorization solution for your applications. Bring your database and have complete control over user information. You can self-host Authorizer instances and connect to any supported database. ![Authorizer Architecture](/img/authorizer-arch.png) #### Features - Sign-in / Sign-up with email ID and password - Secure session management with HTTP-only cookies - Email verification - [OAuth2 and OpenID Connect](./core/oauth2-oidc) compatible APIs - APIs to update profile securely - Forgot password flow using email - Social logins (Google, GitHub, Facebook, LinkedIn, Apple, Discord, Twitter, Twitch, Roblox, Microsoft) - Role-based access management and [fine-grained authorization (FGA)](./core/authorization) via an embedded [OpenFGA](https://openfga.dev) ([Zanzibar](https://research.google/pubs/pub48190/) ReBAC) engine - Password-less login with magic link - [WebAuthn](https://www.w3.org/TR/webauthn-2/) / [passkey](https://fidoalliance.org/passkeys/) registration and login - Multi-factor authentication: [TOTP](https://datatracker.ietf.org/doc/html/rfc6238), email OTP, SMS OTP, and passkey as a second factor - SMS OTP via [Twilio](https://www.twilio.com) - Enterprise SSO — [SAML 2.0](https://www.oasis-open.org/standard/saml/) as Service Provider and Identity Provider, OIDC federation, verified email domains, and home realm discovery ([SSO guide](./core/sso-guide)) - [SCIM 2.0](https://datatracker.ietf.org/doc/html/rfc7644) user and group provisioning ([SCIM](./enterprise/scim)) - [Organizations and multi-tenancy](./enterprise/organizations) with org-scoped admin roles - Machine-to-machine auth (`client_credentials`) and secretless workload identity — [RFC 7523](https://datatracker.ietf.org/doc/html/rfc7523) client assertions, [SPIFFE](https://spiffe.io) JWT-SVIDs, Kubernetes [TokenReview](https://kubernetes.io/docs/reference/kubernetes-api/authentication-resources/token-review-v1/) ([Workload Identity](./enterprise/workload-identity)) - Agent delegation via [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) token exchange ([Token Exchange](./enterprise/token-exchange)) - Email templating and webhooks - Rate limiting, security hardening, and [Prometheus](https://prometheus.io) metrics ([Metrics & Monitoring](./core/metrics-monitoring)) - [GraphQL](./core/graphql-api), [REST](./core/rest-api), and [gRPC](./core/grpc) APIs - [MCP server](./core/mcp) for AI agents #### Introduction Video Watch the introduction video on YouTube: [Introduction to Authorizer](https://www.youtube.com/watch?v=DFgo0TuA4c8) --- ### Authorizer v2 Authorizer v2 focuses on simpler, more secure configuration and a cleaner operational model: - **Configuration via CLI flags only** -- no persisted env in the database or cache - **More secure secret handling** -- secrets are passed at process start, not stored in Authorizer-managed storage - **Stronger defaults and hardening flags** -- better control over GraphQL introspection, admin access, and cookies - **Updated SDKs** -- `@authorizerdev/authorizer-js` v3 and `@authorizerdev/authorizer-react` v2 #### Quick Start ```bash ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` Or with Docker: ```bash docker run -p 8080:8080 \ -v authorizer_data:/authorizer/data \ quay.io/authorizer/authorizer:latest \ --database-type=sqlite \ --database-url=/authorizer/data/data.db \ --url=http://localhost:8080 \ --client-id=123456 \ --client-secret=secret \ --admin-secret=admin \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key ``` Open `http://localhost:8080/app` (login) and `http://localhost:8080/dashboard` (admin secret `admin`). The `authorizer_data` volume keeps the SQLite database across restarts. `--url` is required. An app on another origin, such as a dev server on `http://localhost:3000`, also needs `--allowed-origins=http://localhost:8080,http://localhost:3000`. These values are placeholders for local use only. #### Where to start - **New projects:** Start with the [Getting Started](./getting-started) guide - **Migrating from v1:** See [Migration v1 to v2](./migration/v1-to-v2) for a complete guide - **Deployment:** Choose from [Docker](./deployment/docker), [Kubernetes](./deployment/kubernetes), [Helm Chart](./deployment/helm-chart), or [one-click deploys](./deployment) - **SDK integration:** See [authorizer-js](./sdks/authorizer-js), [authorizer-react](./sdks/authorizer-react), or [authorizer-go](./sdks/authorizer-go) --- ### Supported Databases Authorizer supports a wide range of databases: - PostgreSQL, MySQL, MariaDB, SQLite, libSQL / Turso, SQL Server - MongoDB, ArangoDB, Couchbase, SurrealDB - CassandraDB, ScyllaDB, DynamoDB - Yugabyte, PlanetScale, CockroachDB, SereneDB See [Databases](./core/databases) for connection string formats. --- ### Supported SDKs #### Frontend SDKs - [JavaScript / TypeScript](https://github.com/authorizerdev/authorizer-js) — v4.0.0; user + admin client; GraphQL + REST protocols - [React](https://github.com/authorizerdev/authorizer-react) — v2.2.0; `protocol` prop; pre-built login/signup/MFA components - [Vue](https://github.com/authorizerdev/authorizer-vue) — v2.1.0; no admin client or protocol selection yet - [Svelte](https://github.com/authorizerdev/authorizer-svelte) — v1.1.0; no admin client or protocol selection yet - [Flutter](https://github.com/authorizerdev/authorizer-flutter-sdk) — not released yet; no package on pub.dev #### Backend SDKs - [Go](https://github.com/authorizerdev/authorizer-go) — v2.2.0; user + admin client; protocol selection (gRPC / REST / GraphQL); FGA helpers - [Python](https://github.com/authorizerdev/authorizer-py) — v0.3.0; sync + async; admin API (`pip install authorizer-py`) - [Node.js](https://github.com/authorizerdev/authorizer-js) — same package as the frontend SDK, works server-side See the [SDK reference](./sdks/authorizer-js) for usage docs. --- ### Roadmap - React Native SDK - Android Native SDK - iOS Native SDK - PHP SDK - WordPress plugin - AMI / Digital Ocean Droplet - Azure deployment - Vue / Svelte admin client and protocol parity with authorizer-js --- ## Getting Started This guide helps you start **Authorizer v2** using the **CLI-based configuration model**. If you are upgrading from v1, read the [Migration v1 to v2](../migration/v1-to-v2) guide alongside this page. --- ### Required Variables All examples below use these required variables. Replace with your own values for production: :::info `--encryption-key` (2.4.0+) Encrypts [TOTP](https://datatracker.ietf.org/doc/html/rfc6238) shared secrets and OTP digests at rest. **Required when `--jwt-type` is `RS*`/`ES*`** — with no `--jwt-secret` to fall back to, the server refuses to start without it. With HMAC types (`HS*`) it falls back to `--jwt-secret`, but a distinct value is recommended: rotating the JWT secret otherwise re-keys at-rest data and locks out every enrolled TOTP user. Generate it **once** (`openssl rand -hex 32`), store it as a secret, and keep it stable across restarts — a key that changes on every boot leaves existing TOTP enrolments and pending OTPs undecryptable. Omit the flag on releases before 2.4.0, which do not have it. See [Server Configuration](/core/server-config). ::: | Flag | Description | Sample Value | | ---- | ----------- | ------------ | | `--database-type` | Database type | `sqlite` | | `--database-url` | Database connection string | `test.db` | | `--jwt-type` | JWT signing algorithm | `HS256` | | `--jwt-secret` | JWT signing secret | `test` | | `--encryption-key` | At-rest key for TOTP secrets and OTP digests (2.4.0+). Required with `RS*`/`ES*` | *(generate once with `openssl rand -hex 32`)* | | `--admin-secret` | Admin secret for admin operations | `admin` | | `--client-id` | Client identifier **(required)** | `123456` | | `--client-secret` | Client secret **(required)** | `secret` | > **Important:** `--client-id` and `--client-secret` are **required** in v2. The server does **not** read `.env` files or dashboard-managed env anymore. --- ### Option A: Run from Source #### Prerequisites - Go **>= 1.24** - Node.js **>= 18** (only if building web UIs) - A database (SQLite, Postgres, MySQL, etc.) #### Build and run ```bash git clone https://github.com/authorizerdev/authorizer.git cd authorizer go build -o build/authorizer . ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` For local development: ```bash make dev # or go run main.go \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` --- ### Option B: Docker ```bash docker run -p 8080:8080 \ -v authorizer_data:/authorizer/data \ quay.io/authorizer/authorizer:latest \ --database-type=sqlite \ --database-url=/authorizer/data/data.db \ --url=http://localhost:8080 \ --client-id=123456 \ --client-secret=secret \ --admin-secret=admin \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key ``` Open `http://localhost:8080/app` (login) and `http://localhost:8080/dashboard` (admin secret `admin`). The `authorizer_data` volume keeps the SQLite database across restarts. `--url` is required. An app on another origin, such as a dev server on `http://localhost:3000`, also needs `--allowed-origins=http://localhost:8080,http://localhost:3000`. These values are placeholders for local use only. With PostgreSQL: ```bash docker run -p 8080:8080 quay.io/authorizer/authorizer:latest \ --database-type=postgres \ --database-url="postgres://user:pass@host:5432/authorizer" \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` See [Docker deployment](../deployment/docker) for Docker Compose examples. --- ### Option C: Binary Releases publish the Docker image (Option B), not prebuilt binaries. To run a binary, build it from source (Go and Node.js required) and run it from the repository root, where the login UI, dashboard and email templates live under `web/`: ```bash git clone https://github.com/authorizerdev/authorizer.git && cd authorizer go build -o build/authorizer . && make build-app build-dashboard # Run with required flags ./build/authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` See [Binary deployment](../deployment/binary) for systemd service setup. --- ### Option D: Kubernetes ```bash kubectl apply -f authorizer-v2.yaml ``` See [Kubernetes deployment](../deployment/kubernetes) for full manifests and [Helm Chart](../deployment/helm-chart) for Helm-based installation. --- ### Option E: One-click Deployments | Platform | Deploy Link | | -------- | ----------- | | Railway | [Deploy on Railway](https://railway.com/deploy/authorizer-1?referralCode=FEF4uT&utm_medium=integration&utm_source=template&utm_campaign=generic) | | Heroku | [Deploy to Heroku](https://heroku.com/deploy?template=https://github.com/authorizerdev/authorizer-heroku) | | Render | [Deploy to Render](https://render.com/deploy?repo=https://github.com/authorizerdev/authorizer-render) | | Koyeb | [Deploy to Koyeb](https://app.koyeb.com/deploy?name=authorizer&type=docker&image=quay.io/authorizer/authorizer&env[PORT]=8000&env[DATABASE_TYPE]=postgres&env[DATABASE_URL]=CHANGE_ME&ports=8000;http;/) | See the [Deployment](../deployment/) section for detailed guides for each platform. --- ### Verify it works After starting the server, open: - `http://localhost:8080/app` -- built-in login UI - `http://localhost:8080/graphql` -- GraphQL endpoint (playground if enabled) Since 2.4.0, signup and login offer MFA setup by default: the response says `Proceed to mfa setup` and carries no access token until the user enrols a factor or declines it (`skip_mfa_setup`). For scripted local testing, pass `--disable-mfa` to get tokens directly. Don't disable MFA in production. --- ### Minimal configuration for local development For a quick local dev setup: ```bash ./authorizer \ --env=development \ --http-port=8080 \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --client-id=123456 \ --client-secret=secret \ --admin-secret=admin \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --allowed-origins=http://localhost:8080,http://localhost:3000 ``` List the server's own URL in `--allowed-origins` alongside your app's origin. With an explicit list, state-changing requests (including the built-in login page at `/app`) are accepted only from listed origins. The default `*` accepts them only from the server's own origin, so an app on another port cannot log in until you list it. This example signs tokens with `HS256`, so `/.well-known/jwks.json` is empty (`{"keys":[]}`). If anything validates tokens through JWKS (your API, an MCP server, Hasura), use `RS256` or `ES256` with `--jwt-private-key` and `--jwt-public-key` instead. See [Server Configuration](../core/server-config) for all flags and hardening options. --- ### Frontend SDK versions for v2 When talking to a v2 server, use: - **`@authorizerdev/authorizer-js` v4** (`^4.0.0`) for server 2.4.0 and later. Its only breaking change from v3 is that the admin `deleteUser` takes a user id instead of an email. - **`@authorizerdev/authorizer-react` v2** (`^2.2.1`), which depends on `authorizer-js` v4. ```bash npm install @authorizerdev/authorizer-js@^4.0.0 \ @authorizerdev/authorizer-react@^2.2.1 ``` If you used types directly from `authorizer-js`, rename them for v2: ```ts // Old (v1) import { SignupInput, LoginInput } from '@authorizerdev/authorizer-js' // New (v2 server + v3/v4 SDK) import { SignUpRequest, LoginRequest } from '@authorizerdev/authorizer-js' ``` For more details and a full checklist, see [Migration v1 to v2](../migration/v1-to-v2#6-sdk-and-client-libraries). --- ## Authorization (FGA) ## Authorization (Fine-Grained) Authorizer ships a built-in **fine-grained authorization (FGA)** engine powered by an embedded [OpenFGA](https://openfga.dev) instance — the open-source implementation of Google's [Zanzibar](https://research.google/pubs/pub48190/) relationship-based access control (ReBAC) model. Instead of static `role → permission` tables, you describe your domain as **types** and **relations**, grant access with **relationship tuples**, and ask the engine `Check(user, relation, object)` at request time. FGA is **opt-in** and runs **in-process** — there is no extra service to deploy and no network hop on a check. This page covers: 1. [Enabling FGA](#1-enabling-fga) 2. [The authorization model](#2-the-authorization-model) — types, relations, the DSL, and the dashboard. 3. [Granting access](#3-granting-access--relationship-tuples) — relationship tuples. 4. [Checking access](#4-checking-access--client-api) — `check_permissions`, `list_permissions`. 5. [Admin GraphQL API](#5-admin-graphql-api) — the `_fga_*` operations the dashboard uses. 6. [SDKs](#6-sdks) and [operational notes](#7-operational-notes). 7. [Using FGA from your application](#8-using-fga-from-your-application) — middleware, the tuple lifecycle, list filtering. 8. [Real-world recipes](#9-real-world-recipes) — document sharing, multi-tenant SaaS, job roles, time-bound access, block lists, permission-aware retrieval for RAG/AI agents. 9. [Cheat sheet](#10-cheat-sheet) — app event → FGA operation. --- ### 1. Enabling FGA The engine stores its model and tuples in a SQL datastore. - **SQL main database** (SQLite, Postgres, MySQL, …): FGA is **enabled by default** and reuses your main database. Nothing to configure. - **NoSQL main database** (MongoDB, DynamoDB, …): [OpenFGA](https://openfga.dev) can't use these, so FGA is **disabled** unless you point it at a SQL store with `--fga-store`. | Flag | Purpose | | --- | --- | | `--fga-store` | Override the OpenFGA datastore: `sqlite`, `postgres`, `mysql`, or `memory` (dev only — non-persistent). Defaults to the main database when it is SQL-compatible. | | `--fga-store-url` | Connection URI for an overridden `--fga-store` (a `file:` URI for SQLite, a DSN for Postgres/MySQL). Ignored when FGA reuses the main database. | ```bash # Reuses Postgres main DB — FGA on automatically: authorizer --database-type postgres --database-url "postgresql://..." # MongoDB main DB — give FGA its own Postgres store to turn it on: authorizer --database-type mongodb --database-url "mongodb://..." \ --fga-store postgres --fga-store-url "postgresql://user:pass@host:5432/fga" ``` When FGA is disabled, every FGA GraphQL operation returns `fine-grained authorization is not enabled` and the rest of the server runs normally. --- ### 2. The authorization model The model is your permission **rulebook**. It declares the object **types** you protect, the **relations** on each type (`owner`, `editor`, `viewer`, `can_view`…), and how those relations are computed from one another. You write it once; access is then granted with data (tuples), not by editing the model. It is expressed in OpenFGA's [DSL](https://openfga.dev/docs/configuration-language): ```dsl model schema 1.1 type user type document relations define owner: [user] define editor: [user] or owner define viewer: [user] or editor define can_view: viewer define can_edit: editor define can_delete: owner ``` Reading it: an `owner` is also an `editor` (`or owner`), an `editor` is also a `viewer`, and the permission relations (`can_view`, `can_edit`, `can_delete`) resolve through them. A single `owner` tuple therefore grants view, edit, and delete. The DSL also supports **hierarchies** (`viewer from parent`), **group usersets** (`[user, team#member]`), **public access** (`[user:*]`), and **exclusions** (`viewer but not blocked`), and parameterized **conditions** (ABAC/CEL, `[user with someCondition]`), for example a grant that expires. The server supplies `current_time` on every check. See [Conditions](./fga-guide#conditions-cel--with). #### From the dashboard Open **`/dashboard` → Authorization → Step 1 · Define the model**. Two ways in: - **Roles & permissions** (the default) — a simple matrix: list your roles (`admin`, `editor`, `viewer`) and the actions they can take (`view`, `edit`, `delete`), then tick which role can do what. The dashboard turns the matrix into a valid OpenFGA RBAC model for you — no DSL to learn. It starts from a standard `admin / editor / viewer` set; your configured instance roles (`--roles`) are offered as one-click additions. - **Advanced (DSL)** — the raw editor with a catalog of ready-made examples (document sharing, folder hierarchy, organizations & teams, RBAC, groups, block lists, multi-tenant SaaS, GitHub-style repos, time-bound conditions) and a plain-English summary of whatever you type. #### Versioning There is always exactly **one active model**. Saving creates a new **immutable version** and makes it active; earlier versions are retained so in-flight requests stay valid. OpenFGA models are **append-only** — an individual version cannot be deleted. To change the rules, save a new version. To wipe everything and start over, **reset** the store (see [§7](#7-operational-notes)). --- ### 3. Granting access — relationship tuples A **relationship tuple** is a single fact: _`user` is `relation` of `object`_. Tuples are the data that actually grants access; add and remove them any time without touching the model. | Tuple | Meaning | |-------|---------| | `user:1b9d…` `viewer` `document:1` | This user can view document 1 | | `user:2c8e…` `owner` `document:1` | This user owns document 1 (⇒ editor, viewer) | | `team:9#member` `viewer` `document:1` | Every member of team:9 can view it | | `user:*` `viewer` `document:5` | Document 5 is public | :::info Identify users by id, not name The subject is `user:` — the **Authorizer user id** (the token's `sub` claim, shown on the dashboard's Users page). Names and emails aren't unique and can change; the id is stable. Short ids like `user:1b9d…` on this page abbreviate full UUIDs. ::: Note that FGA relation names are **independent of the instance's `--roles`** (the JWT `roles` claim): app roles stay global and coarse, FGA relations are object-scoped and usually more granular. The dashboard's model builder seeds from your configured roles as a convenience, but the two sets are free to differ. From the dashboard: **Step 2 · Grant access** — add tuples inline, with one-click templates for the common shapes (direct grant, assign a role, grant a whole role, public access, grant-on-a-folder-that-cascades). :::tip To avoid one tuple per object id, grant on a container (`folder`, `organization`) and let resources inherit via a `… from parent` relation, or use `user:*` for public access. ::: --- ### 4. Checking access — client API The client-facing surface is exactly **two queries**. The subject defaults to the **authenticated caller** — resolved server-side from the bearer token or session cookie. An optional `user` ("type:id", or a bare id treated as `user:`) is honored only when the caller is a **super-admin** or when it **equals the caller's own token subject**; anything else is rejected, never silently ignored. A **machine caller** (a `client_credentials` token from a `service_account` client) has its own subject too: it resolves to `service_account:`, not `user:`, so a machine credential presenting its own token can self-check `service_account` tuples the same way a human token self-checks `user` ones. An [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) delegated/token-exchange token follows **its own subject**: delegating a user yields a `user:` subject, while delegating a service account — the agent-to-agent chain — yields `service_account:`. In both cases the decision is additionally intersected with the acting agent, so a delegated caller never exceeds perms(agent) ∩ perms(subject). (Before 2.4.1 a machine-subject delegation resolved to `user:`; see [GHSA-vq29-8q3c-3hrm](https://github.com/authorizerdev/authorizer/security/advisories/GHSA-vq29-8q3c-3hrm).) Model machine identities with `type service_account` and admit it in relevant type restrictions (`viewer: [user, service_account]`) to put them in the same graph as humans; see the [DSL construct reference](./fga-guide#direct-assignment--type-restrictions). An **AI agent acting for a user** (an RFC 8693 delegated token) is checked against *both* `agent:` and `user:`, and needs both to be allowed — its effective authority is `perms(agent) ∩ perms(user)`. This applies to `check_permissions` and `list_permissions` alike, and turns on by declaring `type agent` in your model; deployments without it are unaffected. See [Agent Identity & Permissions](../enterprise/agent-identity). #### `check_permissions` — one or many questions A single check is simply a list of one. Results come back **in order** and echo the checked pair, so batch responses are self-describing. ```graphql query { check_permissions(params: { checks: [ { relation: "can_view", object: "document:1" }, { relation: "can_edit", object: "document:1" } ] }) { results { relation object allowed } } } ``` Each check also accepts optional `contextual_tuples` (evaluated for that one call only, never persisted) — handy for "what-if" checks or request-time facts: ```graphql query { check_permissions(params: { checks: [{ relation: "can_view", object: "document:1", contextual_tuples: [ { user: "user:1b9d…", relation: "viewer", object: "document:1" } ] }] }) { results { relation object allowed } } } ``` #### `list_permissions` — what can I access? Returns the fully-qualified ids of every object of a type the subject holds the permission on — ideal for filtering a list down to what the user may see. ```graphql query { list_permissions(params: { relation: "can_view", object_type: "document" }) { objects # ["document:1", "document:7", ...] permissions { object relation } # (object, relation) detail pairs truncated # true if capped at 1000 entries } } ``` Both filters are optional. Omit `relation`, `object_type`, or both, and every matching (type, relation) pair of the active model is enumerated — an empty input returns **all** permissions the subject holds. The `permissions` field carries the per-relation detail (relevant when no `relation` filter was supplied); `truncated` is `true` when the result was capped at 1000 entries. From the dashboard: open **Users → ⋯ → View Permissions** to run `list_permissions` for any user (the admin session may specify a subject) and see exactly which objects they hold a permission on. #### Gating sessions on permissions — `required_relations` The session and token-validation queries (`session`, `validate_jwt_token`, `validate_session`) accept an optional `required_relations` list of `{ relation, object }` pairs. Each pair is checked against the authenticated caller with **AND semantics, fail-closed** — one denied relation invalidates the whole result. This lets a gateway validate "logged in **and** may edit document 1" in a single call. See the [GraphQL API reference](./graphql-api#validate_jwt_token). --- ### 5. Admin GraphQL API Authoring the model and tuples is an admin task. These operations require the super-admin secret (cookie or `X-Authorizer-Admin-Secret`) and are prefixed `_fga_` to namespace the admin authorization API. The dashboard calls exactly these under the hood, so the UI and the API are interchangeable. | Operation | Type | Purpose | | --- | --- | --- | | `_fga_write_model(params: { dsl })` | mutation | Install a new authorization-model version from its DSL. | | `_fga_get_model` | query | Fetch the active model (id + DSL). | | `_fga_write_tuples(params: { tuples })` | mutation | Add relationship tuples. | | `_fga_delete_tuples(params: { tuples })` | mutation | Remove relationship tuples. | | `_fga_read_tuples(params: { user?, relation?, object?, page_size?, continuation_token? })` | query | Page through stored tuples; empty filter fields act as wildcards. | | `_fga_list_users(params: { object, relation, user_type })` | query | List the users of `user_type` that have a relation on an object (reveals the access graph — admin only). | | `_fga_expand(params: { relation, object })` | query | Expand the relationship/userset tree for a `(relation, object)`, returned as a JSON string (admin only). | | `_fga_reset` | mutation | Delete the model, **all** versions, and **all** tuples, then start a fresh empty store. Refused while any tuple still exists. | ```graphql # Install a model: mutation { _fga_write_model(params: { dsl: "model\n schema 1.1\n\ntype user\n\ntype document\n relations\n define viewer: [user]\n define can_view: viewer" }) { id } } # Grant access: mutation { _fga_write_tuples(params: { tuples: [{ user: "user:1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", relation: "viewer", object: "document:1" }] }) { message } } ``` Full parameter tables and examples for every operation live in the [GraphQL API reference](./graphql-api#authorization-fga). --- ### 6. SDKs The official SDKs expose the read-side client API (model/tuple authoring stays in the dashboard / admin API): - **Go** — `CheckPermissions`, `ListPermissions`. See the [Go SDK guide](/sdks/authorizer-go#step-4-fine-grained-authorization-fga) and the [authorizer-go README](https://github.com/authorizerdev/authorizer-go). - **JavaScript / TypeScript** — `checkPermissions`, `listPermissions`. See the [JS SDK functions](/sdks/authorizer-js/functions#--checkpermissions) and the [authorizer-js README](https://github.com/authorizerdev/authorizer-js). For each, pass the caller's auth header in server contexts; in the browser the session cookie is used automatically. --- ### 7. Operational notes - **Fail closed.** If a check can't be completed (engine disabled, store error), the caller is denied — never silently allowed. - **Resetting.** `_fga_reset` (dashboard: Step 1 → _Danger zone_) is the only way to remove a model and its past versions, because OpenFGA models are append-only. It is **refused while any relationship tuples still exist**, so live grants are never dropped silently — delete the tuples first. The action is audited (`admin.fga_reset`). - **Auditing.** Model writes, tuple writes/deletes, and resets are recorded as admin audit events, visible under **Audit Logs** in the dashboard. - **Metrics.** The engine exports [Prometheus](https://prometheus.io) metrics — `authorizer_fga_checks_total` (allow/deny/error), `authorizer_fga_check_duration_seconds`, and `authorizer_fga_operations_total` — for adoption tracking and denial/error alerting. Delegated (agent) callers additionally report `authorizer_fga_delegated_checks_total{operation,outcome}`, whose `outcome` label is the only thing that distinguishes *the agent lacks a grant* (`denied_by_agent`) from *the user genuinely lacks access* (`denied_by_user`) — and `not_enforced`, which means agent traffic is arriving unconstrained because the model declares no `agent` type. See [Metrics & Monitoring → Authorization (FGA) Metrics](./metrics-monitoring#authorization-fga-metrics) and [Agent Identity & Permissions](../enterprise/agent-identity#observability). - **Learn the model language.** See the OpenFGA docs: [modeling guide](https://openfga.dev/docs/modeling/getting-started) and [configuration language](https://openfga.dev/docs/configuration-language). --- ### 8. Using FGA from your application Your application keeps doing what it does; Authorizer answers one extra question per request: **"may this user do this to this object?"** ```mermaid flowchart LR A["Your app
(frontend)"] -- login --> Auth Auth -- token --> A A -- "API call + token" --> C[Your backend] C -- check_permissions --> Auth subgraph Auth[Authorizer] D[OpenFGA engine] end ``` There are exactly **two touchpoints**: | Touchpoint | When | API | Credential | | --- | --- | --- | --- | | **Write tuples** | On your domain events — a document is created, a user joins a project, someone clicks "Share", access is revoked | `_fga_write_tuples` / `_fga_delete_tuples` | Admin secret, **server-side only** | | **Check access** | On every read/write your backend serves | `check_permissions`, `list_permissions` | The **caller's own token** by default — an explicit `user` is honored only for super-admins or self | #### Writing tuples from your domain events Grant and revoke access by writing tuples when things happen in **your** system — this is the part teams most often miss. Typical lifecycle: | Event in your app | Tuple operation | | --- | --- | | User creates a document | write `user:` `owner` `document:` | | Document is filed in a folder | write `folder:` `parent_folder` `document:` | | User clicks "Share with Bob (can edit)" | write `user:` `editor` `document:` | | User joins an organization | write `user:` `member` `organization:` | | "Make public" toggle | write `user:*` `viewer` `document:` | | Access revoked / user offboarded | `_fga_delete_tuples` the matching tuple(s) | Server-side helper (any language — it's one GraphQL call): ```js // Server-side only: uses the admin secret. async function writeTuples(tuples) { await fetch('https://auth.yourapp.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Authorizer-Admin-Secret': process.env.AUTHORIZER_ADMIN_SECRET, }, body: JSON.stringify({ query: `mutation ($params: FgaWriteTuplesInput!) { _fga_write_tuples(params: $params) { message } }`, variables: { params: { tuples } }, }), }); } // On "document created": await writeTuples([ { user: `user:${creatorId}`, relation: 'owner', object: `document:${docId}` }, ]); ``` #### Checking access in your backend Use the SDKs ([authorizer-js](https://github.com/authorizerdev/authorizer-js), [authorizer-go](https://github.com/authorizerdev/authorizer-go)) or one GraphQL call. Express middleware: ```js import { Authorizer } from '@authorizerdev/authorizer-js'; const auth = new Authorizer({ authorizerURL: 'https://auth.yourapp.com', redirectURL: 'https://yourapp.com', clientID: process.env.AUTHORIZER_CLIENT_ID, }); // requirePermission('can_edit', req => `document:${req.params.id}`) const requirePermission = (relation, objectFor) => async (req, res, next) => { const { data } = await auth.checkPermissions( { checks: [{ relation, object: objectFor(req) }] }, { Authorization: req.headers.authorization }, // forward the caller's token ); if (!data?.results?.[0]?.allowed) return res.status(403).json({ error: 'forbidden' }); next(); }; app.get('/documents/:id', requirePermission('can_view', (req) => `document:${req.params.id}`), getDocumentHandler); app.put('/documents/:id', requirePermission('can_edit', (req) => `document:${req.params.id}`), updateDocumentHandler); ``` The same middleware in Go: ```go func RequirePermission(relation string, objectFor func(*http.Request) string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { res, err := authorizerClient.CheckPermissions(&authorizer.CheckPermissionsRequest{ Checks: []*authorizer.PermissionCheckInput{ {Relation: relation, Object: objectFor(r)}, }, }, map[string]string{"Authorization": r.Header.Get("Authorization")}) if err != nil || len(res.Results) == 0 || !res.Results[0].Allowed { http.Error(w, "forbidden", http.StatusForbidden) // fail closed return } next.ServeHTTP(w, r) }) } } ``` #### Filtering lists — don't check one by one For "show me my documents", ask once and filter your DB query by the result: ```js const { data } = await auth.listPermissions( { relation: 'can_view', object_type: 'document' }, { Authorization: req.headers.authorization }, ); // data.objects => ['document:1', 'document:7', ...] const ids = data.objects.map((o) => o.split(':')[1]); const docs = await db.documents.findMany({ where: { id: { in: ids } } }); ``` For rendering one page with many permission flags (can the user edit? delete? share?), pass several checks to `check_permissions` — one round trip, results in order. --- --- ### 9. Real-world recipes Complete worked scenarios — each with the model, the tuples, and the checks your app runs. Every model below is also a one-click example in the dashboard model editor (**Step 1 → Advanced → Browse examples**) and is validated against the embedded engine in CI. #### Document collaboration (Google-Docs-style sharing) **Scenario.** Users create documents, share them with specific people as editor or viewer, and optionally make them public. **Model** (concentric: an `owner` is an `editor` is a `viewer` — one tuple grants the whole stack): ```dsl model schema 1.1 type user type document relations define owner: [user] define editor: [user] or owner define viewer: [user, user:*] or editor define can_view: viewer define can_edit: editor define can_delete: owner ``` **Your app writes tuples on these events:** ```text # Priya creates doc 42: user:1b9d… owner document:42 # Priya shares with Marco as editor, with Sam as viewer: user:2c8e… editor document:42 user:3d9f… viewer document:42 # Priya hits "anyone with the link can view": user:* viewer document:42 ``` **Your backend checks:** ```text check_permissions(can_edit, document:42) with Marco's token → allowed check_permissions(can_delete, document:42) with Marco's token → denied (owner only) ``` "Unshare" is just `_fga_delete_tuples` on the same tuple. No schema migration, no `document_permissions` join table in your DB. --- #### B2B multi-tenant SaaS (org → project → resource) **Scenario.** Customers are organizations; each has projects containing resources. An org-wide grant must cover everything beneath it — **without one tuple per resource** — while still allowing per-resource exceptions. **Model:** ```dsl model schema 1.1 type user type organization relations define admin: [user] define editor: [user] or admin define viewer: [user] or editor define can_view: viewer define can_edit: editor type project relations define org: [organization] define editor: [user] or editor from org define viewer: [user] or editor or viewer from org define can_view: viewer define can_edit: editor type resource relations define project: [project] define editor: [user] or editor from project define viewer: [user] or editor or viewer from project define can_view: viewer define can_edit: editor ``` **Wire the structure once** (when an org/project/resource is created in your app): ```text organization:101 org project:201 project:201 project resource:301 project:201 project resource:302 ``` **Grant once, high in the tree:** ```text user:1b9d… viewer organization:101 ← ONE tuple ``` Now every check below inherits, with zero per-resource tuples: ```text check_permissions(can_view, resource:301) → allowed (viewer from project ← from org) check_permissions(can_view, resource:302) → allowed check_permissions(can_edit, resource:301) → denied (viewers don't edit) ``` **Fine-grained exception on top** — an external contractor edits one resource only: ```text user:2c8e… editor resource:301 check_permissions(can_edit, resource:301) → allowed check_permissions(can_view, resource:302) → denied (nothing leaks to siblings) ``` When a new resource is created, your app writes **one structural tuple** (`project:201 project resource:303`) and every existing org-level grant applies to it instantly. Tenant isolation falls out of the graph: members of `organization:101` simply have no path to `organization:102` objects. --- #### Approval workflow with job roles **Scenario.** An HR or finance system where `labour`, `manager`, and `executive` staff have escalating permissions on records — managers edit, executives approve and delete. **Model** (`role#assignee` lets you grant a whole role with one tuple): ```dsl model schema 1.1 type user type role relations define assignee: [user] type record relations define labour: [user, role#assignee] define manager: [user, role#assignee] define executive: [user, role#assignee] define can_delete: executive define can_approve: executive define can_edit: manager or can_delete define can_view: labour or can_edit ``` **Tuples:** ```text # Bind each role group to the records it covers (once per record type/instance): role:manager#assignee manager record:88 role:executive#assignee executive record:88 # Onboarding Dana as a manager is now ONE tuple, covering every bound record: user:4e0a… assignee role:manager ``` **Checks:** ```text check_permissions(can_edit, record:88) with Dana's token → allowed check_permissions(can_approve, record:88) with Dana's token → denied ``` Offboarding = delete Dana's one `assignee` tuple; every record access disappears with it. --- #### Time-bound contractor access **Scenario.** A contractor gets access that must expire automatically — no cron job to revoke it. Model the expiry with a [condition](./fga-guide#conditions-cel--with). The grant stops working on its own; the server's clock decides. ```dsl model schema 1.1 type user type document relations define viewer: [user with non_expired_grant] define can_view: viewer condition non_expired_grant(current_time: timestamp, grant_time: timestamp, grant_duration: duration) { current_time < grant_time + grant_duration } ``` ```text user:ctr-9a2… viewer document:sow-2026 with non_expired_grant {grant_time: "2026-11-27T10:00:00Z", grant_duration: "720h"} # after 30 days every check is denied; delete the tuple whenever you want to clean up ``` Alternatives, if you'd rather not use conditions: - **Scheduled revocation.** Grant a plain tuple and have your application call `_fga_delete_tuples` at the expiry time. - **Contextual tuples.** Don't persist the grant: your trusted backend passes the `viewer` tuple as a [contextual tuple](#4-checking-access--client-api) while the window is open. --- #### Suspending a user (block list) **Scenario.** Broad access stays in place, but specific users must be locked out of specific objects — overriding anything else that grants them access. **Model:** ```dsl model schema 1.1 type user type document relations define viewer: [user] define blocked: [user] define can_view: viewer but not blocked ``` ```text user:* viewer document:7 # everyone can read the handbook user:5f1b… blocked document:7 # …except this account check_permissions(can_view, document:7) with 5f1b…'s token → denied ``` `but not` always wins over every grant path — direct, inherited, or public. --- #### Permission-aware retrieval (RAG / AI agents) {#permission-aware-retrieval-rag--ai-agents} **Scenario.** A RAG pipeline or AI agent must never let an LLM see, cite, or summarize a chunk the requesting user isn't allowed to read. The document-collaboration model above is enough — the interesting part is *where* you call FGA relative to ranking. **Two enforcement strategies:** | | Post-filter | Pre-filter | | --- | --- | --- | | How | Rank the whole corpus, then batch `check_permissions` on the top-k candidates | `list_permissions` first, filter the corpus, **then** rank | | Cost | One batched check per query, scoped to candidates only | One list call; grows with the caller's grant count | | Failure mode | **Candidate starvation** — if every top-k hit is denied, few or zero chunks survive | Large grant lists for privileged callers (e.g. an org admin) | | Use when | Corpus ≫ per-user access | Per-user access is small/medium | ```text # Post-filter: rank first, then gate the candidates candidates = bm25_rank(whole_corpus, query, k=4) allowed = check_permissions(checks: [can_view document: for doc in candidates]) context = [c for c in candidates if allowed[c.doc]] # Pre-filter: gate first, then rank only what's visible visible = list_permissions(relation: can_view, object_type: document).objects context = bm25_rank(corpus_filtered_to(visible), query, k=4) ``` As with every other FGA call, **fail closed**: an engine error aborts the query rather than degrading to "show everything," and a `truncated: true` on `list_permissions` must not be treated as the caller's complete allow-list (don't rank as if the tail doesn't exist — page or fall back to post-filter instead). This is also the pattern behind the [MCP server](./mcp)'s `check_permissions` / `list_permissions` tools: the same two calls, invoked by the model itself instead of your retrieval backend. See the runnable [`with-rag-fga`](https://github.com/authorizerdev/examples/tree/main/with-rag-fga) example (Python, both strategies, timed side by side). --- --- ### 10. Cheat sheet App event → FGA operation: | Your app does | You call | | --- | --- | | Serve any protected read/write | `check_permissions` (caller's token) | | Render a list page | `list_permissions`, filter your DB query by the ids | | Render one item with many action buttons | `check_permissions` with several checks | | Create a resource | `_fga_write_tuples`: owner + structural parent tuple | | Share / grant / promote | `_fga_write_tuples`: one tuple | | Revoke / unshare / offboard | `_fga_delete_tuples`: the matching tuple(s) | | Reorganize (move project to new org) | delete + write the structural tuple | | Debug "why can X see Y?" | `_fga_expand` (admin), or **Users → View Permissions** for any subject | --- ## Client Registry Authorizer maintains a **client registry** — one authoritative table of every OAuth client that can authenticate against the instance. It holds two kinds of clients: | Kind | What it is | Grants | |------|------------|--------| | `interactive` | Human-facing login client (browser/app redirect flows). The instance's **reserved client** — seeded at boot from `--client-id` / `--client-secret` — is this kind. | `authorization_code`, `refresh_token` | | `service_account` | Machine/workload identity (backend services, CI jobs, AI agents). Created by admins via the admin API. | `client_credentials`, [token exchange](../enterprise/token-exchange), [CIBA](../enterprise/ciba) (opt-in per client) | `kind` is **immutable** after creation. Clients created through the admin API today are `service_account` clients; the interactive kind is currently reserved for the boot-seeded client, so existing single-client deployments keep working unchanged. ### `client_id` vs. internal `id` Every client has two identifiers: - **`id`** — the internal surrogate primary key (UUID). Used to address the client in admin operations (`_update_client`, `_rotate_client_secret`, …). - **`client_id`** — the public OAuth identifier presented at `/authorize` and `/oauth/token`. Unique across the registry and **immutable**. For admin-created clients, `client_id` defaults to the internal `id` — the UUID returned by `_create_client` is the value you pass as `client_id` at the token endpoint. For the reserved boot client, `client_id` is the literal `--client-id` value, so every existing token `aud` and introspection `client_id` keeps keying on that exact string. (JWKS `kid`s are key thumbprints since v2.4.8, not the client ID; see [JWKS](./oauth2-oidc.md#jwks).) ### Client secrets - Generated server-side; stored only as a **bcrypt hash** (cost 12). - The plaintext is returned **exactly once** — in the `_create_client` response and again in the `_rotate_client_secret` response. It can never be retrieved afterwards; store it in your secret manager immediately. - Rotating a client's secret does **not** affect browser session-cookie encryption (that stays bound to the instance's `--client-secret`). - Secret verification is constant-time; an unknown `client_id` and a wrong secret are indistinguishable to a caller. ### Scopes are an allow-list `allowed_scopes` is the client's authorization ceiling: - A `client_credentials` request may only ask for a **subset** of `allowed_scopes`; anything outside it fails with `invalid_scope` (no silent downgrade). - Omitting `scope` grants the full authorized set. - An **empty allow-list is deny-all** — `_create_client` requires at least one non-empty scope. - In [token exchange](../enterprise/token-exchange), `allowed_scopes` is the agent's delegation ceiling. ### Admin API All operations require super-admin authentication (`x-authorizer-admin-secret` header or the `authorizer.admin` cookie from `_admin_login`) and are also available over gRPC/REST via `AuthorizerAdminService` (`CreateClient`, `UpdateClient`, `DeleteClient`, `RotateClientSecret`, `GetClient`, `Clients` — see the [gRPC reference](./grpc)). | Operation | Type | Purpose | |-----------|------|---------| | `_create_client` | mutation | Register a service account; returns the secret **once** | | `_update_client` | mutation | Update `name`, `description`, `allowed_scopes`, `is_active`, `backchannel_token_delivery_mode` (`"poll"` enables [CIBA](../enterprise/ciba) for the client, `""` disables it; 2.5.0+) | | `_rotate_client_secret` | mutation | Invalidate the old secret, return a new one **once** | | `_delete_client` | mutation | Remove the client | | `_client` | query | Fetch one client by `id` | | `_clients` | query | Paginated list | #### Create a service account ```graphql mutation { _create_client( params: { name: "payments-worker" description: "Nightly settlement job" allowed_scopes: ["read:payments", "write:settlements"] } ) { client { id client_id name allowed_scopes is_active } client_secret # shown ONCE — store it now } } ``` #### Manage clients ```graphql # Disable a client (blocks new token issuance immediately; # already-issued tokens live until their exp) mutation { _update_client(params: { id: "CLIENT_UUID", is_active: false }) { id is_active } } # Rotate the secret mutation { _rotate_client_secret(params: { id: "CLIENT_UUID" }) { client { id } client_secret # the new secret, shown ONCE } } # List query { _clients { pagination { total } clients { id name allowed_scopes is_active created_at } } } ``` Client responses never contain a secret or secret hash — there is no `client_secret` field on the `Client` type by design. The `Client` type does return `client_id` (the public OAuth identifier, distinct from the internal `id`) — add it to any of the queries/mutations above when your caller needs the value to present at `/oauth/token`. ### Authenticating: `client_credentials` Service accounts get tokens with the [RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749) §4.4 grant at `POST /oauth/token`: ```bash curl -s -X POST $AUTHORIZER_URL/oauth/token \ -u "$CLIENT_ID:$CLIENT_SECRET" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials" \ -d "scope=read:payments" ``` ```json { "access_token": "eyJhbG...", "token_type": "Bearer", "expires_in": 1800, "scope": "read:payments" } ``` Rules: - Client authentication via `client_secret_basic` (HTTP Basic) or `client_secret_post` (form body) — never both; presenting more than one method is rejected (RFC 6749 §2.3). - The grant is **machine-only**: an interactive `client_id` is rejected with `unauthorized_client` before secret verification, so it can't be used to confirm a guessed secret. - No `refresh_token`, no `id_token` — re-authenticate on expiry. - Discovery (`/.well-known/openid-configuration`) advertises `client_credentials` in `grant_types_supported`. - Success and failure are both audited (`token.client_credentials` / `token.client_credentials_failed` audit events). - A transient registry lookup failure (e.g. a busy/unreachable database) is never reported as `invalid_client` — that would tell a legitimate caller its credentials are permanently wrong. It returns `503` with `temporarily_unavailable` instead, and is not counted as a security event. ### Service accounts as FGA subjects A `service_account` client authenticated via `client_credentials` can itself be an [OpenFGA](../core/fga-guide) subject. When your authorization model declares a `service_account` type, the machine caller's own `check_permissions` / `list_permissions` calls resolve to the subject `service_account:` — the client's public `client_id`, never its internal `id`: ```dsl type service_account type document relations define viewer: [user, service_account] define can_view: viewer ``` ```graphql # Admin: grant the service account viewer on a document, keyed on its client_id mutation { _fga_write_tuples(params: { tuples: [{ user: "service_account:payments-worker-client-id", relation: "viewer", object: "document:1" }] }) { message } } ``` ```bash # The service account's own client_credentials token then passes check_permissions # as service_account:payments-worker-client-id — no explicit "user" needed. ``` A deactivated (`is_active: false`) service account is denied even while its already-issued token remains cryptographically valid — FGA is an additional, independent gate. A machine caller may only self-pin its own subject (`user: "service_account:"` in `check_permissions`); pinning any other subject is rejected, exactly like a human caller. See the [FGA guide](../core/fga-guide) for the full model/tuple/check walkthrough. ### Secretless authentication: client assertions & trusted issuers Instead of a stored secret, a service account can authenticate with a signed JWT it already possesses — a Kubernetes ServiceAccount token or a [SPIFFE](https://spiffe.io) JWT-SVID — presented as an [RFC 7523](https://datatracker.ietf.org/doc/html/rfc7523) `client_assertion`: ``` POST /oauth/token grant_type=client_credentials &client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer &client_assertion= ``` The assertion is validated against a **trusted issuer** the admin registers for that service account (`_add_trusted_issuer` / `_update_trusted_issuer` / `_delete_trusted_issuer` / `_trusted_issuer` / `_trusted_issuers`): issuer URL, key source (OIDC discovery or a static JWKS URL), expected audience, and an exact-match subject allow-list (empty = deny-all). Setup, validation rules, and Kubernetes/SPIFFE walkthroughs: [Workload Identity](../enterprise/workload-identity). ### Backward compatibility The registry is additive. On upgrade: - The reserved client is seeded idempotently from `--client-id` / `--client-secret` (booting twice, or two instances at once, still yields one row). - Existing tokens keep validating; `aud` stays the configured `--client-id`. - Existing session cookies keep decrypting; cookie crypto is not coupled to per-client secrets. - Discovery and JWKS shapes are unchanged. --- ## Databases ### Supported Databases Authorizer v2 configures the database via CLI flags. The required flags are `--database-type` and `--database-url`. - [Postgres](https://www.postgresql.org/) ```bash --database-type=postgres --database-url="postgres://username:password@localhost:5432/postgres" ``` To keep Authorizer's tables in their own schema, see [Using a Postgres schema](#postgres-schema). - [Yugabyte](https://www.yugabyte.com/) ```bash --database-type=yugabyte --database-url="postgres://username:password@localhost:5432/postgres" ``` - [CockroachDB](https://www.cockroachlabs.com) ```bash --database-type=cockroachdb --database-url="postgres://username:password@localhost:26257/defaultdb" ``` > Use `--database-type=cockroachdb`, not `postgres`: CockroachDB speaks the PostgreSQL wire protocol, but Authorizer needs to know it is CockroachDB to migrate its schema correctly. > > **Already running with `--database-type=postgres`?** Before v2.4.7 these docs showed `postgres` for CockroachDB. That configuration starts once, but every restart fails with `constraint "uni_authorizer_oauth_states_state_key" ... does not exist (SQLSTATE 42704)` and `failed to create storage provider`. Change the flag to `--database-type=cockroachdb` and start again: the existing schema and data are kept, and later restarts work. - [SereneDB](https://www.serenedb.com/) (since v2.4.7) ```bash --database-type=serenedb --database-url="postgres://postgres:password@localhost:7890/postgres" ``` > SereneDB speaks the PostgreSQL wire protocol (default port `7890`). Use SereneDB **26.11 or later**; Authorizer is tested against 26.11.2. Authorizer creates and upgrades its tables with its own versioned migrations, recorded in the `authorizer_schema_migrations` table, instead of the automatic migration it uses on other SQL databases. SereneDB is not an OpenFGA datastore, so to use [fine-grained authorization](./authorization) pass an explicit `--fga-store`. - [SurrealDB](https://surrealdb.com/) (since v2.4.8) ```bash --database-type=surrealdb \ --database-url="https://surreal.example.com" \ --database-username="authorizer" \ --database-password="*********" \ --database-name=authorizer \ --surrealdb-namespace=authorizer ``` > Use SurrealDB **4.0 or later**; Authorizer is tested against 4.0.1. Prefer an `http(s)://` URL: it is stateless, so there is nothing to restore after a dropped connection (`ws(s)://` is also accepted). `--database-name` is the SurrealDB database and `--surrealdb-namespace` (default `authorizer`) its namespace; both are created on first start when the credentials allow it. The credentials can be a root, namespace or database user. Authorizer creates its tables and indexes with its own versioned migrations, recorded in the `authorizer_schema_migrations` table. SurrealDB is not an OpenFGA datastore, so to use [fine-grained authorization](./authorization) pass an explicit `--fga-store`. To let SurrealDB verify Authorizer's tokens for your own tables, see [SurrealDB integration](../integrations/surrealdb). - [MySQL](https://www.mysql.com/) ```bash --database-type=mysql --database-url="username:password@tcp(localhost:port)/database_name" ``` - [PlanetScale](https://planetscale.com/) ```bash --database-type=planetscale --database-url="username:password@tcp(localhost:port)/database_name" ``` - [MariaDB](https://mariadb.org/) ```bash --database-type=mariadb --database-url="username:password@tcp(localhost:port)/database_name" ``` - [SQLite](https://www.sqlite.org/index.html) ```bash --database-type=sqlite --database-url=test.db ``` - [libSQL / Turso](https://turso.tech/) ```bash --database-type=libsql --database-url="libsql://your-db.turso.io?authToken=YOUR_TOKEN" ``` - [SQLServer](https://www.microsoft.com/en-us/sql-server/) ```bash --database-type=sqlserver --database-url="sqlserver://gorm:LoremIpsum86@localhost:9930?database=gorm" ``` - [MongoDB](https://www.mongodb.com) ```bash --database-type=mongodb --database-url="mongodb://localhost:27017" --database-name=authorizer ``` - [ArangoDB](https://www.arangodb.com/) ```bash --database-type=arangodb --database-url="https://root:password@localhost.arangodb.cloud:8529" --database-name=authorizer ``` - [CassandraDB](https://cassandra.apache.org/) ```bash --database-type=cassandradb \ --database-host="db-connection-string" \ --database-username="test" \ --database-password="*********" \ --database-cert="Base64 encoded cert string" \ --database-cert-key="Base64 encoded cert key" \ --database-ca-cert="Base64 encoded CA cert" ``` > Note for CassandraDB: If using a cloud provider like [DataStax](https://www.datastax.com/products/datastax-astra), they don't allow creating `keyspace`. Please create a `keyspace` named `authorizer` from their GUI. > Note for CassandraDB and ScyllaDB: filtering audit logs by `resource_type` or > `resource_id` is served by secondary indexes, which the server creates on > startup (since v2.4.2). On an existing deployment with a large `authorizer_audit_logs` table > those indexes backfill in the background — Scylla builds them as materialized > views — so those two filters can return **incomplete** results until the > backfill completes. Check `nodetool viewbuildstatus` before treating a > filtered audit query as authoritative, and expect elevated cluster I/O while > it runs. Filtering by a `from_timestamp`/`to_timestamp` range cannot use an > index at all (the range is on a non-key column), so it performs a scan with > `ALLOW FILTERING`. So does any query that combines two or more filters, > because one query can use only one index. This is fine for an occasional > admin query and gets slower as the table grows. - [ScyllaDB](https://www.scylladb.com/) ```bash --database-type=scylladb \ --database-host="192.168.0.1,192.168.0.2,192.168.0.3" \ --database-username="scylladb" \ --database-password="*********" ``` - [DynamoDB](https://aws.amazon.com/dynamodb/) ```bash --database-type=dynamodb \ --aws-region=ap-south-1 \ --aws-access-key-id=YOUR_ACCESS_KEY \ --aws-secret-access-key=YOUR_SECRET ``` - [Couchbase](https://www.couchbase.com/) ```bash --database-type=couchbase \ --database-url="couchbase://127.0.0.1" \ --database-username="admin" \ --database-password="*********" \ --couchbase-bucket="authorizer" \ --couchbase-ram-quota=1000 \ --couchbase-scope="_default" ``` > Note for Couchbase: the server creates its secondary indexes (GSIs) on > startup. Couchbase builds an index synchronously, so when a new index is > added against a collection that already holds a lot of data — an upgrade on a > large `authorizer_audit_logs` collection, for example — the statement can > outrun the client. That is handled: the attempt is retried, and because the > index definition is registered server-side the retry sees it already exists > and startup continues while the build finishes in the background. No action > is needed, but index builds may show activity for a while after a version > upgrade. > Note: For MongoDB and ArangoDB, use `--database-name` since the database name is not part of the connection URL. ### Using a Postgres schema {#postgres-schema} By default Authorizer creates its tables in the database's default schema, usually `public`. To keep them in a dedicated schema, for example when Authorizer shares a database with your application, add `search_path` to the connection URL. There is no separate flag for this. ```bash --database-type=postgres \ --database-url="postgres://username:password@localhost:5432/mydb?sslmode=disable&search_path=authz" ``` Create the schema before you start Authorizer. Authorizer does not create it: with a `search_path` that names a schema that doesn't exist, startup fails with `no schema has been selected to create in (SQLSTATE 3F000)`. ```sql CREATE SCHEMA authz; -- If Authorizer connects as a role that does not own the schema: GRANT USAGE, CREATE ON SCHEMA authz TO authorizer_role; ``` When the schema exists, Authorizer creates every table there on first start and uses only that schema from then on. This covers the `authorizer_*` tables and also the [fine-grained authorization](./authorization) (OpenFGA) tables (`store`, `tuple`, `authorization_model`, `assertion`, `changelog`, `goose_db_version`), which share the main database by default. Tables of the same name in `public` are not read or changed. Notes: - Name a single schema, such as `search_path=authz`. A list like `authz,public` is not tested: new tables would go in the first schema, but a table that already exists in a later schema could be found and used. - The `search_path` must stay the same on every start. If you change it, Authorizer creates a new, empty set of tables in the new schema. It does not move existing data. - This was tested with `--database-type=postgres`. CockroachDB, Yugabyte and SereneDB also speak the PostgreSQL protocol, but `search_path` has not been tested with them. ### Tables / Collections Authorizer creates and manages the following tables/collections: - `authorizer_users` -- stores basic user information - `authorizer_verification_requests` -- stores email verification and forgot password requests - `authorizer_sessions` -- stores user sessions ### Session Store For each request requiring authorization, Authorizer validates the HTTP Cookie or Authorization header. To improve throughput, an in-memory store is used. Authorizer supports two session stores: - [Redis](https://redis.io/) -- configured via `--redis-url`. Persisted as long as Redis is running. - In-memory -- default when no Redis URL is set. Not recommended for production. Example with Redis: ```bash ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret \ --redis-url=redis://localhost:6379 ``` --- ## Email Verification Contract ## Email verification contract Authorizer resolves a local account from an email address in several flows — password signup, magic link, and every social/enterprise federated login. This page states when an address counts as **verified**, why federated logins are held to that bar, and what you need to configure. :::warning Behaviour change in 2.4.0 A social login whose provider does not attest the email address is now refused. See [Upgrading](#upgrading) for what to configure if this affects your deployment. ::: ### Why an address must be attested OAuth 2.0 carries no identity claims at all. OpenID Connect added `email` — and alongside it a **separate `email_verified` boolean**, precisely because `email` on its own proves nothing about who controls the mailbox. That distinction matters here because the email address is what selects the local account. It decides signup-versus-login, and the login branch merges the incoming federated identity into whatever account already holds the address. If an attacker can make a provider assert an address they do not own, they land in that account's session. This is the [nOAuth](https://www.descope.com/blog/post/noauth) attack class. Microsoft Entra is the sharp case: - Entra **v2 ID tokens carry no `email_verified` claim at all**. - Entra's `email` is a *mutable, unverified* directory attribute — any tenant admin can set it to any string, including someone else's address. - The multi-tenant endpoints (`common`, `organizations`, `consumers`) sign with Microsoft's **global** keys, so a token minted in a free attacker-owned tenant has a valid signature and a valid `aud`. Only the tenant distinguishes it. So: register a free Entra tenant, set a user's `email` to `victim@example.com`, click "Login with Microsoft", and without this contract you are in the victim's account. ### The three connection classes Authorizer treats connections the same way Auth0 does: | Connection class | Is the address attested? | Behaviour | |---|---|---| | **Database** (password signup) | No — nobody has vouched for it | `email_verified` is `false` until the user clicks the verification link Authorizer mails them (requires `--enable-email-verification=true`; with verification disabled the address is marked verified at signup) | | **Social** (Google, Apple, GitHub, …) | Usually yes — the provider vouches | The provider's own signal is imported directly; no separate verification round-trip | | **Enterprise / Azure AD / OIDC** | **Not guaranteed** — enterprise directories do not promise it | Requires an explicit trust decision from you (see below) | ### Per-provider signal Each provider is read from the signal that provider actually emits. There is no single claim that works everywhere, and treating one provider's silence as another's "true" is exactly what creates the vulnerability. | Provider | Signal | Notes | |---|---|---| | Google | `email_verified` (ID token) | Standard OIDC | | Apple | `email_verified` (ID token) | Documented as "a string or Boolean value" — both forms accepted | | Twitch | `email_verified` (ID token) | Standard OIDC | | LinkedIn | `email_verified` (userinfo) | Both bool and quoted-string forms accepted | | Microsoft | `xms_edov`, **or** a trusted tenant | No `email_verified` exists on Entra v2 — see below | | GitHub | verified by construction | Both the public `/user` email and the `/user/emails` fallback are filtered to verified addresses | ### How a user verifies With `--enable-email-verification`, `signup` creates the verification request and sends the mail before returning "Verification email has been sent. Please check your inbox". Clicking that link is the normal path and needs nothing else. **The link is valid for 30 minutes.** Expiry is enforced when the token is validated, so an expired link is refused even if the underlying request row is still there. :::info Requesting a new link invalidates the old one A link can also stop working *before* its 30 minutes are up. Each request rotates a nonce, and redemption checks the token's nonce against the stored row — so **the most recent link is always the only valid one**. If a user clicks an older link after requesting a fresh one, it will be refused. That is intended, and it is the usual explanation for "the link in my inbox doesn't work" when the user has more than one. ::: If it expires or never arrives: | Route | Who drives it | Notes | |---|---|---| | **`resend_verify_email`** | the user | The primary recovery. Mints a fresh link for the same address, and mints one even when no pending request remains. Gated on the address actually being unverified, so it cannot be used as an open mailer. | | **Password login** | the user | An unverified account's password login emails an OTP instead; verifying that OTP marks the address verified. | | **`_update_user { email_verified: true }`** | an admin | The escape hatch when the user genuinely cannot receive mail. | | Forgot password | the user | Completing a token reset also verifies the address — a side effect of proving mailbox control, not the route to reach for. | None of these needs an administrator except the last. Prefer **Resend Verification Email** over force-verifying: it has the user prove control rather than asserting it on their behalf. The response to a resend is deliberately generic ("if a verification is pending …") and identical whether or not the address exists, so the endpoint cannot be used to test which addresses are registered. ### Hard requirement: verification needs a working email service :::danger `--enable-email-verification=true` with no SMTP configured is a **fatal startup error** in 2.4.0. Every route in the table above terminates at the same mailbox, so without a mail path a user is created unverified and can never recover — and an unverified account also blocks a federated login for that address. Set `--smtp-host`, `--smtp-port` and `--smtp-sender-email` — all three — or turn email verification off. ::: ### This is not the same as Auth0's post-login email check A post-login Action like: ```js exports.onExecutePostLogin = async (event, api) => { if (!event.user.email_verified) { api.access.deny('Please verify your email address before logging in.'); } }; ``` is a **login policy**: "should this user, whoever they are, be let in before confirming their own address?" It is reasonably opt-in, and Authorizer's equivalent is `--enable-email-verification`. What this page describes is **identity resolution**: "which local account does this federated assertion refer to?" Getting that wrong does not inconvenience the legitimate user — it hands their account to somebody else. Which is why the default is secure and the escape hatch is narrowed rather than total. ### What a refusal looks like The callback returns `400` before any local account lookup, so no account is created and no existing account is touched: ```json { "error": "email_not_verified", "error_description": "The identity provider did not confirm that you own this email address." } ``` An `oauth_email_unverified` security metric and an audit event are recorded. ### Upgrading Most deployments need no change — Google, Apple, GitHub, Discord, Facebook, LinkedIn, Twitch, Twitter and Roblox all supply a signal already. **If you use Microsoft login**, pick one: - pin `--microsoft-tenant-id` to your tenant (single-tenant deployments — the common case, and the best option); - set `--microsoft-allowed-tenants` to the tenants you serve (multi-tenant SaaS); - enable the `xms_edov` optional claim in your Entra app registration. #### Compatibility mode If you need more time, `--oauth-allow-unverified-provider-email=true` is a stopgap — existing users keep working and cross-credential takeover stays blocked. It does **not** disable the check. An unattested address still cannot cross into an account owned by another credential; it only re-permits same-provider linking, which leaves two Entra tenants able to collide on one address. The server logs a warning on every boot while it is set. It is not a substitute for one of the three fixes above. ### Operator actions in the dashboard The Users table exposes both operator routes per user, shown only when the relevant identifier is actually unverified: - **Mark Email Verified** — asserts the address is good without mailing anything. Sends only `email_verified`; deliberately not `email`, since that param drives the change-address flow (which clears verification and mails a new link). - **Resend Verification Email** — mails a fresh link so the user proves it themselves. Preferred when you have no independent reason to trust the address. - **Mark Phone Verified** — the phone equivalent. --- ## Email Configuration ## Email ### SMTP Configuration Authorizer can be configured to send emails as part of the authentication flow. For example, to verify a user's email address, to send a user a magic link for password less login, or to allow a user to reset their password. Authorizer should work with any [SMTP](https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol) compliant email server. Please refer to the [Server Configuration](../core/server-config) documentation for the flags required to configure SMTP host, port and authentication. ### Using Sendgrid [Sendgrid](https://sendgrid.com) is configured using an API Key, rather than traditional username/password login. To use Sendgrid you must: 1. Create a Sendgrid account and login 2. Create an API Key for your application under `Settings > API Keys` within the Sendgrid console 3. Ensure that you are using a verified sender email under `Settings > Sender Authentication` within the Sendgrid console. Sendgrid will reject email sent `From:` unverified email addresses. 4. Set the relevant Authorizer configuration flags. You can set them via CLI flags: ```sh --smtp-host=smtp.sendgrid.net --smtp-password= --smtp-port=587 --smtp-username=apikey --smtp-sender-email= ``` > Note: the `--smtp-username` flag must be set to the literal string `apikey` **not** your API key value. --- ## Endpoints Endpoints supported by Authorizer. > Looking for the typed API surface? Every operation is also available as a > [GraphQL API](./graphql-api), a JSON [REST API](./rest-api) under `/v1`, and a native > [gRPC API](./grpc), and a read-only subset is exposed to AI agents via the > [MCP Server](./mcp). ### `/` `GET /` - Root endpoint opens authorize dashboard ### `/.well-known/openid-configuration` `GET /.well-known/openid-configuration` - Returns OPEN ID configuration for instance ### `/.well-known/jwks.json` `GET /.well-known/jwks.json` - To get public key config of JWT token. Used to decode and verify JWT. Recommended to use RS256 JWT type ### `/app` `GET /app` - Application with builtin UI that you can easily integrate in your application. ### `/graphql` `POST /graphql` - GraphQl endpoint for all the [GraphQL queries and mutations](../core/graphql-api) ### `/healthz` `GET /healthz` - Liveness probe. Returns `{"status":"ok"}` with HTTP 200 if the database is reachable, or HTTP 503 with `{"status":"unhealthy"}` otherwise. ### `/readyz` `GET /readyz` - Readiness probe. Returns `{"status":"ready"}` with HTTP 200 if the system is ready, or HTTP 503 with `{"status":"not ready"}` otherwise. ### `/metrics` `GET /metrics` — Prometheus-compatible metrics. **Always** served on a **separate listener** at **`--metrics-host`:`--metrics-port`** (defaults **`127.0.0.1:8081`**); never on the main HTTP port (`--http-port` must differ). See [Metrics & Monitoring](../core/metrics-monitoring) for details. ### `/verify_email` `GET /verify_email?token=TOKEN&redirect_uri=URL` - Endpoint to verify email address This is the endpoint the signup-verification and magic-link emails link to. It works as follows: - Checks `token` and `redirect_uri`. `redirect_uri` must pass `--allowed-origins`, or match exactly when `--redirect-uris` is set. - Marks the email as verified. - Sets the session cookie. - Responds with `307` to `redirect_uri`, adding `state`, `nonce` and, for `/authorize`-started flows opened in the same browser, `code` (redeemable at `/oauth/token` with the PKCE verifier since v2.4.9). Tokens are never put in the redirect URL. Your app reads them with [`session`](./graphql-api#session) using the cookie. If MFA applies to the user, the redirect carries `mfa_required=1&mfa_methods=…&mfa_gate=…` instead and no session cookie is set. See [How the magic link flow works](./graphql-api#magic-link-flow) for the full flow. ### `/userinfo` `GET /userinfo` - Endpoint to get user information. Requires Authorization header with bearer access token ### `/authorize` `GET /authorize` - Endpoint to perform authentication and authorization. It allows perform authentication via builtin login page. - It supports [PKCE flow](https://datatracker.ietf.org/doc/html/rfc7636). This will help user to perform authentication and authorization in safe memory and prevent from CSRF attack. It also enables perform authorization with safety on mobile applications (Tried and tested with [Expo AuthSession](https://github.com/authorizerdev/examples/tree/main/with-react-native-expo)) - It supports [Implicit Flow](https://datatracker.ietf.org/doc/html/rfc6749#section-1.3.2) This end point has following query parameters **Query String Params** | Key | Description | Required | | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `client_id` | Your client_id | true | | `redirect_uri` | URL where user should be redirected after login | true | | `response_type` | What type of response you want. It supports `code` & `token` as response types. Default value is `token` | false | | `code_challenge` | SHA-256 challenge used to verify the code that will be sent. Required when `code` flow is used | false | | `state` | Unique state identifier that is used to make sure request is not interrupted | true | | `scope` | Space separated list of openID scopes. If not present default scopes `openid email profile` is used | false | | `response_mode` | Response is required in which format. Supports 2 forms `query` (returns redirect url with response in query string) and `web_message` (returns html page with data embedded in JS). Default its value is `query` | false | | `screen_hint` | Specifies a hint to the authorization server about the desired user interaction screen. When set to `signup` the authorization server will redirect the user to the signup page of the authentication provider | false | Response is typically a web page with code / token details or redirection to expected url with token as query params ### `/oauth/token` `POST /oauth/token` - Endpoint used to get the token information when oauth & openid flow is performed. > Note: Valid browser session is required to get token information in case `grant_type` authorization_code is used **Request Body Params** | Key | Description | Required | | --------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------- | | `grant_type` | Supports `authorization_code` & `refresh_token` grant types. Default is `authorization_code` | false | | `code_verifier` | Code verifier to verify against the code_challenge sent in authorize request. Required if `authorization_code` flow is used. | false | | `code` | Code returned form authorize request is sent to make sure it is follow up of same request | false | | `refresh_token` | Refresh token used to get the new access token. Required in case of `refresh_token` grant type | false | **Response** | Key | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | | `scope` | List of openID scopes | ### `oauth/revoke` **Request Body Params** | Key | Description | Required | | --------------- | --------------------------- | -------- | | `refresh_token` | Refresh token to be revoked | true | **Response** | Key | Description | | --------- | --------------- | | `message` | Success message | ### `/oauth_login/:oauth_provider` `GET /oauth_login/:oauth_provider` - Endpoint to perform oauth login for various providers like google, github, facebook This endpoint supports following query parameters **Query String Params** | Key | Description | Required | | -------------- | --------------------------------------------------------------------------------------------------- | -------- | | `redirect_uri` | URL where user should be redirected after login. See accepted values below | true | | `redirectURL` | Deprecated alias of `redirect_uri`, still accepted | false | | `state` | Unique state identifier that is used to make sure request is not interrupted | true | | `roles` | Comma separated list of roles to login with. If not present default role(`user`) is used | false | | `scope` | Space separated list of openID scopes. If not present default scopes `openid email profile` is used | false | Sample URLs: ``` # Outside /authorize: return to your app (its origin is in --allowed-origins) /oauth_login/google?redirect_uri=https://myapp.com/dashboard&state=abc123&roles=admin # From the login page during an /authorize request: return to /app, which resumes /authorize /oauth_login/google?state=st-123&redirect_uri=https%3A%2F%2Fauth.example.com%2Fapp%2F%3Fclient_id%3Dc1%26response_type%3Dcode%26state%3Dst-123%26... ``` More cases, with the result for each, are in [What `/oauth_login` accepts](./oauth2-oidc#social-login-inside-an-authorization-request). **Accepted `redirect_uri` values:** - Any URI allowed by `--allowed-origins`. - This server's own `/app`, `/app/` or `/app/signup` (same scheme and host:port as `--url`, exact path, no fragment), whatever `--allowed-origins` says. _Authorizer 2.4.6 and later._ The login page uses this to resume an `/authorize` request through `/authorize`, which then checks the client's registered redirect URIs. See [Social login inside an authorization request](./oauth2-oidc#social-login-inside-an-authorization-request). A client's registered redirect URI is **not** accepted here unless its origin is in `--allowed-origins`. To get a code to a registered client, go through `/authorize`. ### `/oauth_callback/:oauth_provider` `GET /oauth_callback/:oauth_provider` - Endpoint that is used by oauth providers as callback after success / unsuccessful login. Register `/oauth_callback/` as the callback URL on the provider's console. On success it sets the session cookie and redirects to the `redirect_uri` given to `/oauth_login`: - For this server's own `/app` URL, it redirects to that URL unchanged and issues no authorization code. `/app` resumes the original `/authorize` request. - For any other URI, it appends `state` and `nonce`, plus `code` when the login belongs to an `/authorize` request. That last case is deprecated: it skips the consent screen and logs a warning. ### `logout` `GET logout` - Endpoint to logout user This endpoint supports following query parameters **Query String Params** | Key | Description | Required | | -------------- | ------------------------------------------------ | -------- | | `redirect_uri` | URL where user should be redirected after logout | false | --- ## FGA Guide — Examples & Patterns A hands-on companion to the [Authorization (FGA) reference](./authorization). That page explains *what* the engine is and the full API surface; this one is a cookbook — from a first working model to every relationship construct the DSL supports, each with the tuples to write and the checks that exercise it, shown in raw GraphQL and in the [Go](https://github.com/authorizerdev/authorizer-go) and [JavaScript](https://github.com/authorizerdev/authorizer-js) SDKs. 1. [Setup](#setup) 2. [Part 1 — A document-sharing app, end to end](#part-1--a-document-sharing-app-end-to-end) 3. [Part 2 — Advanced patterns](#part-2--advanced-patterns) 4. [Part 3 — DSL construct reference](#part-3--dsl-construct-reference) 5. [Limits & behavior](#limits--behavior) ### Setup FGA needs a SQL store ([details](./authorization#1-enabling-fga)). With SQLite it is on by default — this is all you need to follow along: ```bash docker run -p 8080:8080 quay.io/authorizer/authorizer:latest \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` Two API surfaces are involved (full reference: [client API](./authorization#4-checking-access--client-api), [admin API](./authorization#5-admin-graphql-api)): | Surface | Operations | Credential | | --- | --- | --- | | **Admin** — author the model, grant/revoke | `_fga_write_model`, `_fga_write_tuples`, `_fga_delete_tuples`, … | Admin secret (`X-Authorizer-Admin-Secret` header), server-side only | | **Client** — answer "may this user…?" | `check_permissions`, `list_permissions` | The caller's own token / session cookie | All examples below use `http://localhost:8080/graphql`. Subjects are `user:` where `` is the **Authorizer user id** (the token's `sub` claim) — short ids like `user:1b9d…` abbreviate full UUIDs. --- ### Part 1 — A document-sharing app, end to end The "hello world" of ReBAC: users create documents, share them as editor or viewer. #### Step 1 — Define the model Three role relations and three permission relations. The roles are **concentric** (`or owner` / `or editor`): one `owner` tuple grants edit and view too. ```dsl model schema 1.1 type user type document relations define owner: [user] define editor: [user] or owner define viewer: [user] or editor define can_view: viewer define can_edit: editor define can_delete: owner ``` **Dashboard** — open `http://localhost:8080/dashboard` → **Authorization → Step 1 · Define the model**. Either use the default **Roles & permissions** matrix (no DSL — tick which role can do what) or switch to **Advanced (DSL)**, where "Document sharing" is a one-click example. Save to install. **GraphQL** (admin): ```bash curl http://localhost:8080/graphql \ -H 'Content-Type: application/json' \ -H 'X-Authorizer-Admin-Secret: admin' \ -H 'Origin: http://localhost:8080' \ -d '{ "query": "mutation ($params: FgaWriteModelInput!) { _fga_write_model(params: $params) { id } }", "variables": { "params": { "dsl": "model\n schema 1.1\n\ntype user\n\ntype document\n relations\n define owner: [user]\n define editor: [user] or owner\n define viewer: [user] or editor\n define can_view: viewer\n define can_edit: editor\n define can_delete: owner" } } }' ``` :::note CSRF: send an Origin header `POST /graphql` is CSRF-protected — state-changing requests need a matching `Origin` (or `Referer`) header even when called server-to-server with the admin secret. Both example apps in the [examples repo](https://github.com/authorizerdev/examples) (`with-fga-permissions`, `with-fga-advanced`) set `Origin` on every request for exactly this reason. ::: #### Step 2 — Grant access (write tuples) Priya creates document 1 and shares it: Marco can edit, Sam can view. | user | relation | object | | --- | --- | --- | | `user:1b9d…` (Priya) | `owner` | `document:1` | | `user:2c8e…` (Marco) | `editor` | `document:1` | | `user:3d9f…` (Sam) | `viewer` | `document:1` | **Dashboard** — **Authorization → Step 2 · Grant access**, add the three tuples (the "direct grant" template fills the shape for you). **GraphQL** (admin — your backend calls this on its own "create"/"share" events): ```graphql mutation { _fga_write_tuples(params: { tuples: [ { user: "user:1b9d…", relation: "owner", object: "document:1" } { user: "user:2c8e…", relation: "editor", object: "document:1" } { user: "user:3d9f…", relation: "viewer", object: "document:1" } ] }) { message } } ``` Revoking is the mirror image — `_fga_delete_tuples` with the same tuple. #### Step 3 — Check permissions The subject is the **authenticated caller** — resolved from the bearer token / session cookie you send. Batch several questions in one call; results come back in order. **GraphQL** (with Marco's token in the `Authorization` header): ```graphql query { check_permissions(params: { checks: [ { relation: "can_view", object: "document:1" } { relation: "can_edit", object: "document:1" } { relation: "can_delete", object: "document:1" } ] }) { results { relation object allowed } } } ``` Expected (Marco is `editor`): ```json { "results": [ { "relation": "can_view", "object": "document:1", "allowed": true }, { "relation": "can_edit", "object": "document:1", "allowed": true }, { "relation": "can_delete", "object": "document:1", "allowed": false } ] } ``` **Go SDK**: ```go import "github.com/authorizerdev/authorizer-go/v2" client, _ := authorizer.NewAuthorizerClient("123456", "http://localhost:8080", "", nil) res, err := client.CheckPermissions(&authorizer.CheckPermissionsRequest{ Checks: []*authorizer.PermissionCheckInput{ {Relation: "can_view", Object: "document:1"}, {Relation: "can_edit", Object: "document:1"}, {Relation: "can_delete", Object: "document:1"}, }, }, map[string]string{"Authorization": "Bearer " + marcoToken}) if err != nil { /* fail closed: deny */ } for _, r := range res.Results { fmt.Println(r.Relation, r.Object, r.Allowed) // can_view true, can_edit true, can_delete false } ``` **JavaScript SDK**: ```js import { Authorizer } from '@authorizerdev/authorizer-js'; const authorizer = new Authorizer({ authorizerURL: 'http://localhost:8080', redirectURL: 'http://localhost:3000', clientID: '123456', }); const { data, errors } = await authorizer.checkPermissions( { checks: [ { relation: 'can_view', object: 'document:1' }, { relation: 'can_edit', object: 'document:1' }, { relation: 'can_delete', object: 'document:1' }, ], }, { Authorization: `Bearer ${marcoToken}` }, // in the browser the session cookie is used automatically ); // data.results → [ {allowed: true}, {allowed: true}, {allowed: false} ] ``` #### Step 4 — List what a user can access Ideal for list pages: ask once, filter your DB query by the returned ids. **GraphQL** (with Sam's token): ```graphql query { list_permissions(params: { relation: "can_view", object_type: "document" }) { objects # ["document:1"] truncated # false } } ``` **Go SDK**: ```go res, err := client.ListPermissions(&authorizer.ListPermissionsRequest{ Relation: "can_view", ObjectType: "document", }, map[string]string{"Authorization": "Bearer " + samToken}) // res.Objects → ["document:1"] ``` **JavaScript SDK**: ```js const { data } = await authorizer.listPermissions( { relation: 'can_view', object_type: 'document' }, { Authorization: `Bearer ${samToken}` }, ); // data.objects → ["document:1"] data.truncated → false ``` Both filters are optional: omit `relation` to get every permission the subject holds on that type, omit both to enumerate everything (see [Limits](#limits--behavior)). From the dashboard, **Users → ⋯ → View Permissions** runs the same query for any user. --- ### Part 2 — Advanced patterns Each pattern: the DSL, the tuples, and checks with expected results. The patterns compose — the [hierarchy example](#org--team--project-hierarchy) uses three of them at once. (Checks below are GraphQL/SDK calls exactly as in Part 1; shown compactly as `check(subject, relation, object)`.) #### Org → team → project hierarchy Combines **tuple-to-userset** (`admin from org`, `lead from team`), a **userset subject** (`team:eng#member` as the *user* of a tuple), and **computed relations**. ```dsl model schema 1.1 type user type organization relations define admin: [user] define member: [user] type team relations define org: [organization] define member: [user] or admin from org define lead: [user] type project relations define team: [team] define editor: [user] or lead from team define viewer: [user, team#member] or editor define can_view: viewer define can_edit: editor ``` Tuples — wire the structure once, then grant on the highest sensible level: ```text user:1b9d… admin organization:acme # Priya is org admin organization:acme org team:eng # team eng belongs to acme user:2c8e… member team:eng # Marco is on team eng user:3d9f… lead team:eng # Sam leads team eng team:eng team project:rocket # project rocket belongs to team eng team:eng#member viewer project:rocket # ALL of team eng can view rocket ``` Checks and why: ```text check(user:2c8e…, can_view, project:rocket) → allowed (member of team:eng → in team:eng#member → viewer) check(user:2c8e…, can_edit, project:rocket) → denied (member, not lead) check(user:3d9f…, can_edit, project:rocket) → allowed (lead from team) check(user:1b9d…, can_view, project:rocket) → allowed (org admin → team member via "admin from org" → team:eng#member) ``` One `member team:eng` tuple on a new hire grants every project the team is wired to. A multi-level variant of this (org → project → resource with per-resource exceptions) is worked through in [Real-world recipes](./authorization#9-real-world-recipes). #### Groups as subjects A tuple's *user* can be a **userset** — "everyone who has relation R on object O": ```dsl model schema 1.1 type user type team relations define member: [user] type document relations define viewer: [user, team#member] define can_view: viewer ``` ```text user:2c8e… member team:eng team:eng#member viewer document:roadmap # one tuple, whole team check(user:2c8e…, can_view, document:roadmap) → allowed list(user:2c8e…, can_view, document) → ["document:roadmap"] ``` Adding someone to `team:eng` instantly grants every document the team holds; removing their one `member` tuple revokes it all. #### Public access (wildcard) `[user:*]` in a type restriction lets you write a tuple whose subject is *every* user: ```dsl model schema 1.1 type user type document relations define owner: [user] define viewer: [user, user:*] or owner define can_view: viewer ``` ```text user:* viewer document:handbook # "anyone with the link" check(, can_view, document:handbook) → allowed ``` The wildcard is per-object — only `document:handbook` is public. Note `user:*` means "all users", not a pattern: `user:1b9d*` is not a thing. #### Exclusion — block lists (`but not`) Deny specific users regardless of any other grant path: ```dsl model schema 1.1 type user type document relations define viewer: [user, user:*] define blocked: [user] define can_view: viewer but not blocked ``` ```text user:* viewer document:7 user:5f1b… blocked document:7 check(user:5f1b…, can_view, document:7) → denied (blocked beats the public grant) check(user:2c8e…, can_view, document:7) → allowed ``` `but not` wins over every grant path — direct, inherited, group, or public. #### Intersection — require both (`and`) Allowed only when the subject satisfies **every** operand: ```dsl model schema 1.1 type user type document relations define approver: [user] define legal_reviewer: [user] define can_publish: approver and legal_reviewer ``` ```text user:1b9d… approver document:contract user:1b9d… legal_reviewer document:contract user:2c8e… approver document:contract check(user:1b9d…, can_publish, document:contract) → allowed (both relations) check(user:2c8e…, can_publish, document:contract) → denied (approver only) ``` #### Contextual tuples — request-time facts Each entry in `check_permissions.checks` accepts `contextual_tuples`: tuples evaluated **for that one check only, never persisted**. Use them for facts your app knows at request time (current device, IP-derived region, an in-progress "what if I shared this?" preview) without writing to the store. Contextual tuples are asserted by the caller, so a caller can always grant itself the relation it is checking. Pass them only from your trusted backend. A delegated (agent) token may not send them: the request is rejected, so an agent can't talk its way past a "check before acting" guardrail. Model — viewing requires *both* a grant and a trusted device (intersection): ```dsl model schema 1.1 type user type document relations define viewer: [user] define trusted_device: [user] define can_view: viewer and trusted_device ``` Stored tuple: `user:2c8e… viewer document:1`. Your backend asserts the device check as a contextual tuple: **GraphQL**: ```graphql query { check_permissions(params: { checks: [{ relation: "can_view" object: "document:1" contextual_tuples: [ { user: "user:2c8e…", relation: "trusted_device", object: "document:1" } ] }] }) { results { relation object allowed } # allowed: true — without the contextual tuple: false } } ``` **Go SDK**: ```go res, err := client.CheckPermissions(&authorizer.CheckPermissionsRequest{ Checks: []*authorizer.PermissionCheckInput{{ Relation: "can_view", Object: "document:1", ContextualTuples: []*authorizer.FgaTupleInput{ {User: "user:2c8e…", Relation: "trusted_device", Object: "document:1"}, }, }}, }, headers) ``` **JavaScript SDK**: ```js const { data } = await authorizer.checkPermissions( { checks: [{ relation: 'can_view', object: 'document:1', contextual_tuples: [ { user: 'user:2c8e…', relation: 'trusted_device', object: 'document:1' }, ], }], }, headers, ); ``` Contextual tuples are available on `check_permissions` only — `list_permissions` always evaluates against stored tuples. #### Roles as objects — grant a whole role at once When several object instances should follow the same role assignment, model the role itself as an object and bind its `assignee` userset: ```dsl model schema 1.1 type user type role relations define assignee: [user] type record relations define manager: [user, role#assignee] define can_edit: manager ``` ```text role:manager#assignee manager record:88 # bind the role to the record role:manager#assignee manager record:89 user:4e0a… assignee role:manager # onboard Dana: ONE tuple, both records check(user:4e0a…, can_edit, record:88) → allowed check(user:4e0a…, can_edit, record:89) → allowed ``` Offboarding deletes one tuple. (`role:` objects are the one place where the object id is a name by design; everywhere else use stable ids.) FGA roles are independent of the instance's `--roles` JWT claim — see [the note on roles](./authorization#3-granting-access--relationship-tuples). --- ### Part 3 — DSL construct reference Every relationship-definition construct [OpenFGA](https://openfga.dev)'s DSL (`schema 1.1`) supports, and how it behaves through `check_permissions` / `list_permissions`. All of these are verified against Authorizer's embedded engine — except where explicitly marked unsupported. | Construct | Syntax | Grants access to | | --- | --- | --- | | [Direct assignment](#direct-assignment--type-restrictions) | `define viewer: [user]` | Subjects with a stored tuple for this exact relation | | [Type restrictions](#direct-assignment--type-restrictions) | `[user, service_account]` | Tuples whose subject is one of the listed types | | [Wildcard](#wildcard-public-access) | `[user:*]` | Every subject of that type, once a `user:*` tuple exists | | [Userset subject](#userset-subjects) | `[team#member]` | Everyone holding `member` on the referenced `team` | | [Union](#union-or) | `a or b` | Subjects matching *any* operand | | [Intersection](#intersection-and) | `a and b` | Subjects matching *every* operand | | [Exclusion](#exclusion-but-not) | `a but not b` | Subjects matching `a` and **not** `b` | | [Computed userset](#computed-userset) | `define can_view: viewer` | Whoever holds the referenced relation on the same object | | [Tuple-to-userset](#tuple-to-userset-x-from-y) | `viewer from parent` | Whoever holds `viewer` on the object's `parent` | | [Conditions](#conditions-cel--with) | `[user with cond]` | Subjects whose tuple condition holds (e.g. an unexpired grant) | #### Direct assignment & type restrictions ```dsl define viewer: [user] define auditor: [user, service_account] ``` The bracket list is a **type restriction**: only tuples whose subject matches a listed type may be written. `_fga_write_tuples` validates every tuple against the active model — writing `service_account:ci viewer document:1` against `viewer: [user]` is rejected with an error, not silently dropped. A relation with no direct type restriction (e.g. a pure computed relation like `define can_view: viewer`) cannot be the relation of any stored tuple. Check behavior: `check(user:X, viewer, document:1)` is true iff the tuple `user:X viewer document:1` exists (or another construct in the same definition grants it). #### Wildcard (public access) ```dsl define viewer: [user, user:*] ``` Allows the tuple `user:* viewer document:1`, after which **every** subject of type `user` passes `check(…, viewer, document:1)`, and `document:1` appears in everyone's `list_permissions` result. The wildcard must be declared in the type restriction — against plain `[user]`, writing a `user:*` tuple is rejected. #### Userset subjects ```dsl define viewer: [user, team#member] ``` Allows tuples whose subject is a **userset** — `team:eng#member viewer document:1` — granting to everyone who holds `member` on `team:eng`, resolved at check time. Group membership changes propagate instantly to every grant of the userset; no tuple fan-out. #### Union (`or`) ```dsl define editor: [user] or owner ``` True if **any** operand grants. This is how concentric roles are built (`owner` ⇒ `editor` ⇒ `viewer`): grant the strongest relation with one tuple and the weaker ones follow. `list_permissions` reflects the union — an owner sees the object listed under an `editor` filter too. #### Intersection (`and`) ```dsl define can_publish: approver and legal_reviewer ``` True only if **every** operand grants. See the [worked example](#intersection--require-both-and). With `list_permissions`, an object is listed only for subjects satisfying all operands. #### Exclusion (`but not`) ```dsl define can_view: viewer but not blocked ``` True if the left side grants **and** the right side does not. The exclusion overrides every other path (direct, group, inherited, wildcard). Excluded objects also disappear from the subject's `list_permissions` results. :::tip Combining operators Keep each `define` to a single operator and name intermediate relations (`define viewer: [user] or editor`, then `define can_view: viewer but not blocked`) instead of mixing `or` / `and` / `but not` in one expression. It reads better and side-steps precedence questions entirely. ::: #### Computed userset ```dsl define viewer: [user] define can_view: viewer ``` `can_view` has no tuples of its own; it *is* `viewer` on the same object. Use it to separate **role** relations (granted by tuples) from **permission** relations (what code checks) — your handlers keep checking `can_view` even when its definition evolves. #### Tuple-to-userset (`X from Y`) ```dsl type folder relations define viewer: [user] type document relations define parent: [folder] define viewer: [user] or viewer from parent ``` "Whoever is `viewer` of this document's `parent`." Requires (1) a linking relation (`parent: [folder]`) and a structural tuple `folder:f1 parent document:1`, and (2) the referenced relation (`viewer`) defined on the linked type. Chains transitively across levels — see the [hierarchy example](#org--team--project-hierarchy). The linking relation must be a direct relation (it cannot itself be computed). ```text folder:f1 parent document:1 user:2c8e… viewer folder:f1 check(user:2c8e…, viewer, document:1) → allowed ``` #### Conditions (CEL / `with`) A **condition** is a CEL expression declared in the model. A type restriction `[user with condition_name]` makes a tuple grant access only while its condition holds. The classic use is a grant that expires: ```dsl model schema 1.1 type user type document relations define viewer: [user with non_expired_grant] define can_view: viewer condition non_expired_grant(current_time: timestamp, grant_time: timestamp, grant_duration: duration) { current_time < grant_time + grant_duration } ``` **Write a conditional tuple** by attaching the condition name and its stored parameters (`_fga_write_tuples` only): ```graphql mutation { _fga_write_tuples(params: { tuples: [{ user: "user:2c8e…", relation: "viewer", object: "document:sow-2026", condition: { name: "non_expired_grant", context: { grant_time: "2026-11-27T10:00:00Z", grant_duration: "720h" } } }] }) { message } } ``` `_fga_read_tuples` returns the stored `condition { name context }`; a plain tuple returns `condition: null`. Revoke by deleting the tuple by `user`, `relation` and `object` (a condition on a delete is rejected). **Checks need no changes.** `check_permissions`, `list_permissions` and every internal check evaluate conditions automatically. **Rules that keep conditions trustworthy:** - `current_time` is always the server's clock (RFC 3339, UTC). Callers can't set it on a check, and it can't be stored on a tuple; both are rejected. A caller-supplied time would revive an expired grant, and a stored one would never expire. - Store **every** condition parameter except `current_time` on the tuple; a write that leaves one out is rejected. `list_permissions`, `required_relations` and the SAML and org-role lookups can only supply `current_time`, so an unbound parameter would make those fail. - A model that declares `current_time` with a type other than `timestamp` is rejected. - Parameters stored on a tuple take precedence over request context, so a check can't override `grant_time` or `grant_duration`. - `check_permissions` accepts an optional `context` **from a super-admin only**. It is not accepted from a delegated (agent) token, and any other caller sending it gets a permission error. Because stored parameters win, it can't change the outcome of a stored condition. - Contextual tuples can't carry a condition. Don't combine conditional and plain grants on one relation (`[user, user with cond]`) if untrusted callers can send contextual tuples: a plain contextual tuple satisfies the relation even after the conditional grant expires. --- --- ### Limits & behavior | Behavior | Detail | | --- | --- | | **Batch size** | `check_permissions` accepts at most **100** checks per request. | | **List cap** | `list_permissions` returns at most **1000** entries; `truncated: true` signals more exist. Prefer setting both `relation` and `object_type` — an unfiltered call enumerates every (type, relation) pair in the model. | | **Fail closed** | Any engine error denies the whole call — an error response is a deny, never an implicit allow. | | **Subject trust gate** | The subject is the caller's token subject. An explicit `user` parameter is honored only for super-admins or when it equals the caller's own subject; anything else errors. | | **Tuple validation** | `_fga_write_tuples` validates each tuple against the active model (type exists, relation defined, subject type allowed). | | **Response shape** | `list_permissions` returns `objects`, `permissions { object relation }`, and `truncated` — surfaced identically by the Go (`Objects`/`Permissions`/`Truncated`) and JS SDKs. | | **Model changes** | Saving a model creates a new immutable active version; tuples are kept. See [versioning](./authorization#2-the-authorization-model) and [reset semantics](./authorization#7-operational-notes). | **Debugging a decision** — the admin-only [`_fga_expand` and `_fga_list_users`](./authorization#5-admin-graphql-api) queries reveal *why* a check passes (the full userset tree / every subject holding a relation), and the dashboard's **Users → View Permissions** shows any user's access at a glance. Engine throughput and allow/deny rates are exported as [Prometheus metrics](./metrics-monitoring#authorization-fga-metrics). **Further reading** — [Authorization (FGA) reference](./authorization) · [Real-world recipes](./authorization#9-real-world-recipes) · [OpenFGA modeling guide](https://openfga.dev/docs/modeling/getting-started) · [OpenFGA configuration language](https://openfga.dev/docs/configuration-language). --- ## GraphQL API Authorizer instance supports GraphQL natively and thus helps you share the common schema for your frontend applications. You can play with GraphQL API using the GraphQL playground that comes with your Authorizer instance. Access GraphQL playground on the instance same as of your Authorizer instance URL. > Note super admin only queries / mutations starts with underscore `_`. Table of Contents - [GraphQL API](./graphql-api) - [Public APIs](#public-apis) - [Queries](#queries) - [`meta`](#meta) - [`session`](#session) - [`profile`](#profile) - [`validate_jwt_token`](#validate_jwt_token) - [`validate_session`](#validate_session) - [`check_permissions`](#check_permissions) - [`list_permissions`](#list_permissions) - [Mutations](#mutations) - [`signup`](#signup) - [`login`](#login) - [`magic_link_login`](#magic_link_login) - [`logout`](#logout) - [`update_profile`](#update_profile) - [`verify_email`](#verify_email) - [`resend_verify_email`](#resend_verify_email) - [`forgot_password`](#forgot_password) - [`reset_password`](#reset_password) - [`revoke`](#revoke) - [`verify_otp`](#verify_otp) - [`resend_otp`](#resend_otp) - [`verify_totp`](#verify_totp) - [`deactivate_account`](#deactivate_account) - [Authorizer Admin APIs](#authorizer-admin-apis) - [Admin Authentication](#admin-authentication) - [`_admin_login`](#_admin_login) - [`_admin_logout`](#_admin_logout) - [`_admin_session`](#_admin_session) - [`_admin_meta`](#_admin_meta) - [Users](#users) - [`_users`](#_users) - [`_user`](#_user) - [`_update_user`](#_update_user) - [`_delete_user`](#_delete_user) - [`_verification_requests`](#_verification_requests) - [Access Control](#access-control) - [`_revoke_access`](#_revoke_access) - [`_enable_access`](#_enable_access) - [`_invite_members`](#_invite_members) - [Webhooks](#webhooks) - [`_add_webhook`](#_add_webhook) - [`_update_webhook`](#_update_webhook) - [`_delete_webhook`](#_delete_webhook) - [`_webhook`](#_webhook) - [`_webhooks`](#_webhooks) - [`_webhook_logs`](#_webhook_logs) - [`_test_endpoint`](#_test_endpoint) - [Email Templates](#email-templates) - [`_add_email_template`](#_add_email_template) - [`_update_email_template`](#_update_email_template) - [`_delete_email_template`](#_delete_email_template) - [`_email_templates`](#_email_templates) - [Audit Logs](#audit-logs) - [`_audit_logs`](#_audit_logs) - [Authorization (FGA)](#authorization-fga) - [`_fga_write_model`](#_fga_write_model) - [`_fga_get_model`](#_fga_get_model) - [`_fga_write_tuples`](#_fga_write_tuples) - [`_fga_delete_tuples`](#_fga_delete_tuples) - [`_fga_read_tuples`](#_fga_read_tuples) - [`_fga_list_users`](#_fga_list_users) - [`_fga_expand`](#_fga_expand) - [`_fga_reset`](#_fga_reset) ### Public APIs #### Queries #### `meta` Query to get the `meta` information about your authorizer instance. eg, version, configurations, etc It returns `Meta` type with the following possible values | Key | Description | | --------------------------------- | ------------------------------------------------------------- | | `version` | Authorizer version that is currently deployed | | `client_id` | Identifier for your instance | | `is_google_login_enabled` | It gives information if google login is configured or not | | `is_github_login_enabled` | It gives information if github login is configured or not | | `is_facebook_login_enabled` | It gives information if facebook login is configured or not | | `is_discord_login_enabled` | It gives information if discord login is configured or not | | `is_email_verification_enabled` | It gives information if email verification is enabled or not | | `is_basic_authentication_enabled` | It gives information, if basic auth is enabled or not | | `is_magic_link_login_enabled` | It gives information if password less login is enabled or not | | `is_sign_up_enabled` | It gives information if sign up is enabled or not | | `is_totp_mfa_enabled` | Whether [TOTP](https://datatracker.ietf.org/doc/html/rfc6238) MFA enrollment and login are available | | `is_email_otp_mfa_enabled` | Whether email OTP MFA enrollment and login are available (requires SMTP configured) | | `is_sms_otp_mfa_enabled` | Whether SMS OTP MFA enrollment and login are available (requires [Twilio](https://www.twilio.com) configured) | | `is_webauthn_enabled` | Whether [WebAuthn](https://www.w3.org/TR/webauthn-2/)/passkey enrollment is available | **Sample Query** ```graphql query { meta { version client_id is_google_login_enabled is_github_login_enabled is_facebook_login_enabled is_discord_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_totp_mfa_enabled is_email_otp_mfa_enabled is_sms_otp_mfa_enabled is_webauthn_enabled } } ``` #### `session` Query to get the `session` information. > Note: Session information should be present as HTTP Cookie. If the information is not present or an invalid data is present it throws `unauthorized` error This query can take a optional input `params` of type `SessionQueryInput` which includes `roles` to verify if the current token is valid for a given roles. **Request Params** | Key | Description | Required | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `roles` | Array of string with valid roles | false | | `scope` | List of openID scopes. If not present default scopes ['openid', 'email', 'profile'] is used | false | | `required_relations` | `[FgaRelationInput!]` — each `{ relation!, object! }`. Gates the session on [fine-grained authorization](./authorization): every pair is checked against the authenticated caller with AND semantics, fail-closed. Requires FGA enabled. | false | It returns `AuthResponse` type with the following keys. **Response** | Key | Description | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `message` | Error / Success message from server | | `should_show_email_otp_screen` | Boolean value for frontend application to show otp input for email based login screen | | `should_show_mobile_otp_screen` | Boolean value for frontend application to show otp input for mobile based login screen | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | | `user` | User object with all the basic profile information | **Sample Query** ```graphql query { session(params: { roles: ["admin"] }) { message access_token expires_in user { id email roles } } } ``` #### `profile` Query to get the `profile` information of a user. It returns `User` type with the following keys. > Note: this is authorized route, so Authorization Header with bearer access token must be present or HTTPs cookie should be present. | Key | Description | | ------------------------------ | ------------------------------------------------------------ | | `id` | user unique identifier | | `email` | email address of user | | `given_name` | first name of user | | `family_name` | last name of user | | `signup_methods` | methods using which user have signed up, eg: `google,github` | | `email_verified` | timestamp at which the email address was verified | | `picture` | profile picture URL | | `roles` | List of roles assigned to user | | `middle_name` | middle name of user | | `nickname` | nick name of user | | `preferred_username` | preferred username (defaults to email currently) | | `gender` | gender of user | | `birthdate` | birthdate of user | | `phone_number` | phone number of user | | `phone_number_verified` | if phone number is verified | | `created_at` | timestamp at which the user entry was created | | `updated_at` | timestamp at which the user entry was updated | | `app_data` | extra information with respect to your application | | `revoked_timestamp` | timestamp at which the user access was revoked | | `is_multi_factor_auth_enabled` | identifies if multifactor auth is enabled for user | **Sample Query** ```graphql query { profile { given_name family_name email picture roles } } ``` #### `validate_jwt_token` Query to validate the given jwt token. This query needs input `params` of type `ValidateJWTTokenInput` **Request Parameters** | Key | Description | Required | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `token_type` | Type of token that needs to be validated. One of `access_token`, `refresh_token`, `id_token`. | `true` | | `token` | JWT string | `true` | | `roles` | Array of roles to validate the JWT token for | `false` | | `required_relations` | `[FgaRelationInput!]` — each `{ relation!, object! }`. Gates validation on [fine-grained authorization](./authorization): AND semantics, fail-closed. Requires FGA enabled. | `false` | It returns `ValidateJWTTokenResponse` type with the following keys. **Response** | Key | Description | | ---------- | ---------------------------------------------------------- | | `is_valid` | Boolean indicating if given token was valid or not | | `claims` | JSON object of the claims in token. [authorizer >= 1.1.23] | **Sample Query** ```graphql query { validate_jwt_token(params: { token_type: "access_token", token: "some jwt token", required_relations: [{ relation: "can_edit", object: "document:1" }] }) { is_valid claims } } ``` #### `validate_session` Query to validate the browser session. This query needs input `params` of type `ValidateSessionInput` **Request Parameters** | Key | Description | Required | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `cookie` | Browser cookie. Either the browser HTTP cookie is present or this parameter must be supplied. | `false` | | `roles` | Array of roles to validate session for | `false` | | `required_relations` | `[FgaRelationInput!]` — each `{ relation!, object! }`. Gates validation on [fine-grained authorization](./authorization): AND semantics, fail-closed. Requires FGA enabled. | `false` | It returns `ValidateSessionResponse` type with the following keys. **Response** | Key | Description | | ---------- | ----------------------------------------------------------- | | `is_valid` | Boolean indicating if given session/cookie was valid or not | **Sample Query** ```graphql query { validate_session(params: { cookie: "" }) { is_valid } } ``` #### `check_permissions` > `check_permissions` and `list_permissions` answer authorization questions against the embedded FGA (ReBAC) engine. They require a valid session or bearer token. The subject is pinned server-side from the caller's token/cookie; the optional `user` is honored only for super-admins or when it equals the caller's own subject. See [Authorization (FGA)](./authorization) for the full model. Evaluate one or more permission checks in a single call. Returns `{ results { relation object allowed } }`, positionally aligned with `checks` and echoing each pair. Input `CheckPermissionsInput`: | Key | Description | Required | | -------- | -------------------------------------------------------------------------------------------------------- | -------- | | `checks` | `[PermissionCheckInput!]!` — each `{ relation!, object!, contextual_tuples? }`. | `true` | | `user` | Subject ("type:id", bare id → `user:`). Honored only for super-admins or self; defaults to the caller. | `false` | ```graphql query { check_permissions(params: { checks: [ { relation: "can_view", object: "document:1" }, { relation: "can_edit", object: "document:1" } ] }) { results { relation object allowed } } } ``` Each check accepts optional `contextual_tuples` — extra tuples evaluated for that one check only and never persisted. Useful for "what-if" checks and request-time facts: ```graphql query { check_permissions(params: { checks: [ { relation: "can_view", object: "document:1", contextual_tuples: [ { user: "user:1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", relation: "viewer", object: "document:1" } ] } ] }) { results { relation object allowed } } } ``` #### `list_permissions` List what the subject can access. With both `relation` and `object_type` set it answers "which `object_type`s can I `relation`?". Either or both filters may be omitted — every matching (type, relation) pair of the active model is then enumerated, so an empty input returns **all** permissions the subject holds. Input `ListPermissionsInput`: | Key | Description | Required | | ------------- | -------------------------------------------------------------------------------------------------------- | -------- | | `relation` | Relation to list for (e.g. `can_view`). Omit to enumerate every relation of the active model. | `false` | | `object_type` | Object type to enumerate (e.g. `document`). Omit to enumerate every type of the active model. | `false` | | `user` | Subject ("type:id", bare id → `user:`). Honored only for super-admins or self; defaults to the caller. | `false` | **Response** `ListPermissionsResponse`: | Key | Description | | ------------- | --------------------------------------------------------------------------------------------------------------------- | | `objects` | Distinct fully-qualified object ids the subject holds the queried permission on (e.g. `["document:1", "document:7"]`). | | `permissions` | The `(object, relation)` detail pairs — relevant when no `relation` filter was supplied. | | `truncated` | `true` when the result was capped (1000 entries) and more permissions exist. | ```graphql query { list_permissions(params: { relation: "can_view", object_type: "document" }) { objects permissions { object relation } truncated } } ``` `FgaTupleInput` (used by `contextual_tuples` above and by the admin operations) is `{ user: String!, relation: String!, object: String! }`. #### Mutations #### `signup` A mutation to signup users using email and password. It accepts `params` of type `SignUpInput` with following keys as parameter. Either `email` or `phone_number` is required to signup **Request Params** | Key | Description | Required | | ------------------ | ------------------------------------------------------------------------------------------- | -------- | | `email` | Email address of user | false | | `password` | Password that user wants to set | true | | `confirm_password` | Value same as password to make sure that its user and not robot | true | | `given_name` | First name of the user | false | | `family_name` | Last name of the user | false | | `picture` | Profile picture URL | false | | `roles` | List of roles to be assigned. If not specified `DEFAULT_ROLE` value of env will be used | false | | `middle_name` | middle name of user | false | | `nickname` | nick name of user | false | | `gender` | gender of user | false | | `birthdate` | birthdate of user | false | | `phone_number` | phone number of user | false | | `scope` | List of openID scopes. If not present default scopes ['openid', 'email', 'profile'] is used | false | | `redirect_uri` | URI where the user should be redirected after signup verification | false | This mutation returns `AuthResponse` type with following keys **Response** | Key | Description | | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `message` | Success / Error message from server | | `should_show_email_otp_screen` | Boolean value for frontend application to show otp input for email based login screen | | `should_show_mobile_otp_screen` | Boolean value for frontend application to show otp input for mobile based login screen | | `access_token` | Token that can be used for further authorized requests. This is only returned if `DISABLE_EMAIL_NOTIFICATION` is set to `true` in environment variables | | `expires_in` | Timestamp when the access Token will expire so that frontend can request new token. This is only returned if `DISABLE_EMAIL_NOTIFICATION` is set to `true` in environment variables | | `user` | User object with its profile keys mentioned [above](#profile). This is only returned if `DISABLE_EMAIL_NOTIFICATION` is set to `true` in environment variables | **Sample Mutation** ```graphql mutation { signup( params: { email: "foo@bar.com", password: "test", confirm_password: "test" } ) { message } } ``` #### `login` A mutation to login users using email and password. It accepts `params` of type `LoginInput` with following keys as parameter. Either `email` or `phone_number` is required to login > Note: To enable MFA, go to dashboard and enable MFA for user. By default, TOTP MFA will be enabled. If SMTP details are provided then Mail OTP can also be enabled. One can only enable one MFA at a time. > Every second factor is verified with the same [`verify_otp`](#verify_otp) mutation — pass `is_totp: true` for an authenticator code, and omit it for an email or SMS code. **Request Params** | Key | Description | Required | | -------------- | ------------------------------------------------------------------------------------------- | -------- | | `email` | Email address of user | false | | `phone_number` | Phone number of user | false | | `password` | Password that user wants to set | true | | `roles` | Roles to login with | false | | `scope` | List of openID scopes. If not present default scopes ['openid', 'email', 'profile'] is used | false | This mutation returns `AuthResponse` type with following keys **Response** | Key | Description | | ------------------------------- |---------------------------------------------------------------------------------------------------------------------------------------------------| | `message` | Success / Error message from server | | `should_show_email_otp_screen` | Boolean value for frontend application to show otp input for email based login screen | | `should_show_mobile_otp_screen` | Boolean value for frontend application to show otp input for mobile based login screen | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | | `user` | User object with its profile keys mentioned [above](#profile). | | `authenticator_scanner_image` | If TOTP enrollment is in progress, a base64 QR image that can be scanned with an authenticator app | | `authenticator_secret` | The TOTP shared secret, for entering by hand when a QR code cannot be scanned | | `authenticator_recovery_codes` | Recovery codes, returned once when TOTP enrollment completes | **Sample Mutation** ```graphql mutation { login(params: { email: "foo@bar.com", password: "test" }) { user { email given_name family_name picture roles } access_token expires_in message } } ``` #### `magic_link_login` A mutation to perform password less login. It accepts `params` of type `MagicLinkLoginInput` with following keys as parameter. When the operation is successful, it sends user email with magic link to login. This link is valid for 30 minutes only. > Note: You will need a SMTP server with an email address and password configured as authorizer environment using which system can send emails. **Request Params** | Key | Description | Required | | -------------- | ------------------------------------------------------------------------------------------- | -------- | | `email` | Email address of user | true | | `roles` | Roles to login with | false | | `scope` | List of openID scopes. If not present default scopes ['openid', 'email', 'profile'] is used | false | | `redirect_uri` | URL where user should be redirect after email verification | false | | `state` | Unique string used to verify OAuth state | false | This mutation returns `Response` type with following keys **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { magic_link_login(params: { email: "foo@bar.com" }) { message } } ``` ##### How the magic link flow works {#magic-link-flow} **1. Server configuration.** Start the server with all of these: `--enable-magic-link-login`, `--enable-email-verification`, and a working SMTP setup (`--smtp-host`, `--smtp-port`, `--smtp-sender-email`). If `--enable-email-verification` is off, `magic_link_login` still returns its usual success message but **no email is sent**. The response message is the same whether or not the account exists, so the mutation can't be used to find out which emails are registered. The exception is when signup is disabled: an unknown email then gets an error. **2. Choosing the redirect URL.** The redirect URL is chosen in this order: 1. The `redirect_uri` you pass to `magic_link_login`. 2. Otherwise `<--url>/app`, the built-in login UI. There is no `APP_URL` / `--app-url` setting in v2. A `redirect_uri` you pass must pass the `--allowed-origins` check ([server config](./server-config)). With the default `--allowed-origins=*`, only URLs on the server's own `--url` origin are accepted. To send users to an app on a different origin, add that origin to `--allowed-origins`. A rejected `redirect_uri` returns `invalid redirect URI`. The server then adds `roles` (and `state` and `scope` when you pass them) to the redirect URL as query parameters. Pass a `redirect_uri` without its own query string. **3. The emailed link.** The email contains a link to the server, valid for 30 minutes and usable once: ```text https:///verify_email?redirect_uri=&roles=user&state=&token= ``` Since v2.4.9 every value is URL-encoded and `roles`, `state` and `scope` are separate parameters. Up to v2.4.8 they were appended, unencoded, to the `redirect_uri` itself. The `token` is a single-purpose verification token. It is not an access token. Don't try to use it as a credential. **4. The user clicks the link.** [`GET /verify_email`](./endpoints#verify_email) does the following: - Checks the `redirect_uri` again and checks the token (signature, expiry, purpose, and that the request hasn't been used). - Marks the email as verified and logs the user in. If MFA applies, it stops here and sends the user to the MFA step instead (see **MFA** below). - Sets the Authorizer **session cookie** in the browser. - Responds with `307` to the redirect URL, adding only `state`, `nonce` and (see below) `code`: ```text https://your-app.example.com/auth/callback?state=&nonce= ``` **The redirect URL never contains `access_token`, `id_token` or `refresh_token`.** Tokens used to be added to this URL. Because the URL starts from an email, it ends up in mail-client and browser history, proxy logs and `Referer` headers, so tokens were removed from it ([GHSA-44vr-f829-xfch](https://github.com/authorizerdev/authorizer/security/advisories/GHSA-44vr-f829-xfch)). The session cookie is how the login reaches your app. **5. Your app gets tokens.** On the redirect page, call [`session`](#session) (`getSession` in authorizer-js) with credentials included. The browser sends the session cookie and the response contains `access_token`, `id_token`, `user` and so on. Each call to `session` rotates the session cookie, so always let the browser store the new `Set-Cookie` (`credentials: 'include'` does this). ```js import { Authorizer } from '@authorizerdev/authorizer-js' const authRef = new Authorizer({ authorizerURL: 'https://auth.example.com', redirectURL: 'https://your-app.example.com/auth/callback', clientID: 'YOUR_CLIENT_ID', }) // Login page: request the email. await authRef.magicLinkLogin({ email: 'foo@bar.com', redirect_uri: 'https://your-app.example.com/auth/callback', }) // /auth/callback page (where /verify_email redirects to): const { data, errors } = await authRef.getSession() if (data?.access_token) { // logged in: data.user, data.access_token, data.id_token } ``` The session cookie belongs to the Authorizer domain. If your app runs on a different site, `getSession` is a cross-site request that carries a cookie. It depends on `--app-cookie-same-site` (default `none`) and on the browser allowing third-party cookies, the same as any other cookie-based Authorizer login. **Authorization code flow (`/authorize` + PKCE).** If you start the magic-link login with the same `state` used at [`/authorize`](./endpoints#authorize), `/verify_email` adds a `code` to the redirect. Since v2.4.9 that code is exchanged at `/oauth/token` like any other authorization code: it is single-use and needs the PKCE `code_verifier`. A code is issued only when both of these hold: - The link is opened **in the same browser that started `/authorize`**. `/authorize` sets a short-lived, HttpOnly binding cookie, so opening the link on another device or in another browser still signs the user in (session cookie) but adds no `code`. - The redirect target is **exactly** the `redirect_uri` that `/authorize` recorded. When no code is issued, run `/authorize` again from your app (for example `authRef.authorize({ response_type: 'code', ... })`). The browser now has a session cookie, so `/authorize` redirects straight back with a code. Up to v2.4.8 the code added by `/verify_email` could not be exchanged (`/oauth/token` returned `invalid_grant`); use the same re-run of `/authorize` there. **Exact redirect URIs (`--redirect-uris`).** When `--redirect-uris` is set, `/verify_email` requires the `redirect_uri` to match a registered URI exactly. Since v2.4.9 the emailed link carries the `redirect_uri` unchanged, so magic-link login works with exact redirect URIs. Up to v2.4.8 the link appended `?roles=...` to the `redirect_uri`, the match failed with `400 invalid redirect uri`, and you had to use `--allowed-origins` instead. **MFA.** MFA is on by default, so expect this step on a user's first magic link. `/verify_email` withholds the session when any of these is true: - The user has enrolled a second factor. - `--enforce-mfa` is set. - MFA applies to the user and they have not skipped setup yet. In that case it sets no session cookie. It sets a short-lived (3-minute) MFA session cookie instead and redirects to the redirect URL with `mfa_required=1`, `mfa_methods=` and `mfa_gate`. The `state`, `nonce` and `code` parameters are not added. For example: ```text https://your-app.example.com/auth/callback?mfa_gate=offer&mfa_methods=totp%2Cwebauthn%2Cemail_otp&mfa_required=1 ``` `mfa_gate=verify` means the user must prove a factor they already enrolled. `mfa_gate=offer` means they are offered enrollment and may skip it. Your page completes the step with the MFA mutations, such as [`verify_otp`](#verify_otp), or [`skip_mfa_setup`](#skip_mfa_setup) for an `offer`. Those calls identify the user from the MFA session cookie and return the tokens, after which `getSession` works as above. The built-in `/app` UI handles these parameters. If you don't want the MFA step, start the server with `--disable-mfa`. If the user's MFA is locked, the redirect carries an `error` parameter instead. #### `logout` Mutation to logout user. This is authorized request and accepts `token` as HTTP cookie or Authorization header with `Bearer token`. This action clears the session data from server. It returns `Response` type with following keys **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { logout { message } } ``` #### `update_profile` Mutation to update profile of user. It accepts `params` of type `UpdateProfileInput` with following keys as parameter > Note: this is authorized route and Authorization with bearer access token is required **Request Params** | Key | Description | Required | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `given_name` | New first name of the user | false | | `family_name` | New last name of the user | false | | `email` | New email of th user. This will logout the user and send the new verification mail to user if `DISABLE_EMAIL_NOTIFICATION` is set to false | false | | `old_password` | In case if user wants to change password they need to specify the older password here. In this scenario `newPassword` and `confirmNewPassword` will be required. | false | | `newPassword` | New password that user wants to set. In this scenario `old_password` and `confirmNewPassword` will be required | false | | `confirmNewPassword` | Value same as the new password to make sure it matches the password entered by user. In this scenario `old_password` and `newPassword` will be required | false | | `middle_name` | New middle name of user | false | | `nickname` | New nick name of user | false | | `gender` | New gender of user | false | | `birthdate` | New birthdate of user | false | | `phone_number` | New phone number of user | false | This mutation returns `Response` type with following keys **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { update_profile(params: { given_name: "bob" }) { message } } ``` #### `verify_email` Mutation to verify email address of user. It accepts `params` of type `VerifyEmailInput` with following keys as parameter **Request Params** | Key | Description | Required | | ------- | ----------------------------- | -------- | | `token` | Token sent for verifying user | true | This mutation returns `AuthResponse` type with following keys **Response** | Key | Description | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `message` | Success / Error message from server | | `should_show_email_otp_screen` | Boolean value for frontend application to show otp input for email based login screen | | `should_show_mobile_otp_screen` | Boolean value for frontend application to show otp input for mobile based login screen | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | | `user` | User object with its profile keys mentioned [above](#profile). | **Sample Mutation** ```graphql mutation { verify_email(params: { token: "some token" }) { user { email given_name family_name picture } access_token expires_in message } } ``` #### `resend_verify_email` Mutation to resend verification email. This is helpful if user does not receive verification email. It accepts `params` of type `ResendVerifyEmailInput` with following keys as parameter **Request Params** | Key | Description | Required | | ------------ | ------------------------------------------------------------------------------------------------------------------------------ | -------- | | `email` | Email on which the verification email is not received | true | | `identifier` | Which type of verification request it is. `basic_auth_signup`, `update_email`, `forgot_password` are the supported identifiers | true | This mutation returns `Response` type with following keys **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { resend_verify_email( params: { email: "foo@bar.com", identifier: "basic_auth_signup" } ) { message } } ``` #### `forgot_password` Mutation to reset the password in case user have forgotten it. For security reasons this is 2 step process, we send email to the registered and then the are redirect to reset password url through the link in that email. In the first step, it accepts `params` of type `ForgotPasswordInput` with following keys as parameter **Request Params** | Key | Description | Required | | ------- | -------------------------------------------- | -------- | | `email` | Email for which password needs to be changed | true | This mutation returns `Response` type with following keys **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { forgot_password(params: { email: "foo@bar.com" }) { message } } ``` #### `reset_password` Mutation to reset the password. For security reasons this is 2 step process, we send email to the registered and then the are redirect to reset password url through the link in that email. In the second step, it accepts `params` of type `ResetPasswordInput` with following keys as parameter On success, this also synchronously revokes all of the user's existing sessions and refresh tokens — see [Refresh tokens](./security#refresh-tokens). **Request Params** | Key | Description | Required | | ------------------ | --------------------------------------------------------------------------- | -------- | | `token` | Token sent via email in step 1 | true | | `password` | New password that user wants to set | true | | `confirm_password` | Same as password just to make sure the values match and is entered by human | true | This mutation returns `Response` type with following keys **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { reset_password( params: { token: "some token", password: "test", confirm_password: "test" } ) { message } } ``` #### `revoke` Mutation to revoke refresh token. **Request Params** | Key | Description | Required | | --------------- | ----------------------------------- | -------- | | `refresh_token` | Refresh token that needs to revoked | true | ```graphql mutation { revoke(params: { refresh_token: "token" }) { message } } ``` #### `verify_otp` Mutation to verify OTP sent to the user. It accepts `params` of type `VerifyOTPRequest` with following keys as parameter **Request Params** | Key | Description | Required | | -------------- | -------------------------------------------------- | -------- | | `email` | Email address of user | false | | `phone_number` | Phone number of user | false | | `otp` | OTP (One Time Password) sent to user email address | true | | `is_totp` | Set `true` when the code came from an authenticator app rather than email/SMS. Also completes TOTP enrollment after `totp_mfa_setup` | false | | `state` | Authorization-code grant flow state, to obtain a `code` for an in-progress `/authorize` request | false | Either `email` or `phone_number` is required This mutation returns `AuthResponse` type with following keys **Response** | Key | Description | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `message` | Success / Error message from server | | `should_show_email_otp_screen` | Boolean value for frontend application to show otp input for email based login screen | | `should_show_mobile_otp_screen` | Boolean value for frontend application to show otp input for mobile based login screen | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | | `user` | User object with its profile keys mentioned [above](#profile). | **Sample Mutation** ```graphql mutation { verify_otp(params: { email: "foo@bar.com", otp: "AB123C" }) { user { email given_name family_name picture roles } access_token expires_in message } } ``` #### `resend_otp` Mutation to resend OTP to the user. It accepts `params` of type `ResendOTPRequest` with following keys as parameter **Request Params** | Key | Description | Required | | -------------- | --------------------- | -------- | | `email` | Email address of user | false | | `phone_number` | Phone number of user | false | Either `email` or `phone_number` is required This mutation returns `Response` type with following keys **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { resend_otp(params: { email: "foo@bar.com" }) { message } } ``` #### `skip_mfa_setup` Completes an in-progress, token-withheld MFA first-time-setup offer by recording that the caller explicitly declined it, then issues the access token that was withheld (see [Withheld-token first-time setup](../core/security#withheld-token-first-time-setup)). Accepts `params` of type `SkipMfaSetupRequest`. **Request Params** | Key | Description | Required | | -------------- | ------------------------------------------------------------- | -------- | | `email` | Email address of the user (resolves the pending MFA session) | false | | `phone_number` | Phone number of the user (resolves the pending MFA session) | false | | `state` | Authorization-code-grant state, same as `verify_otp` | false | Either `email` or `phone_number` is required. Returns `AuthResponse` (same shape as [`verify_otp`](#verify_otp)). Fails with an error when MFA is org-enforced (`--enforce-mfa`) — enforcement is never skippable. ```graphql mutation { skip_mfa_setup(params: { email: "foo@bar.com" }) { access_token expires_in message } } ``` #### `lock_mfa` Records that the caller lost access to their only enrolled MFA factor(s), permanently locking the account until an admin recovers it (see [Lockout & admin recovery](../core/security#lockout--admin-recovery)). Only allowed when the caller has no verified email/SMS OTP fallback enrolled — use that instead of locking if one exists. Does **not** issue a token. Accepts `params` of type `LockMfaRequest`. **Request Params** | Key | Description | Required | | -------------- | ----------------------- | -------- | | `email` | Email address of the user | false | | `phone_number` | Phone number of the user | false | Either `email` or `phone_number` is required. Returns `Response`. ```graphql mutation { lock_mfa(params: { email: "foo@bar.com" }) { message } } ``` #### `email_otp_mfa_setup` Sends a one-time code to the caller's own email and creates an unverified email-OTP MFA enrollment; verify it with [`verify_otp`](#verify_otp) to activate. Accepts `params` of type `OtpMfaSetupRequest`. Dual-mode: with a valid bearer token/session, `params` is ignored and the code goes to the already-authenticated caller (the settings-screen "add a second factor" flow); without one, `email`/`phone_number` resolve the pending MFA session cookie (the withheld first-time-setup flow). **Request Params** | Key | Description | Required | | -------------- | -------------------------------------------------------------------- | -------- | | `email` | Email address (MFA-session-cookie mode only; ignored when bearer-authenticated) | false | | `phone_number` | Phone number (MFA-session-cookie mode only; ignored when bearer-authenticated) | false | Returns `Response`. ```graphql mutation { email_otp_mfa_setup(params: { email: "foo@bar.com" }) { message } } ``` #### `sms_otp_mfa_setup` Sends a one-time code to the caller's own phone number and creates an unverified SMS-OTP MFA enrollment. Same dual-mode permissions and `verify_otp` activation relationship as [`email_otp_mfa_setup`](#email_otp_mfa_setup). Accepts `params` of type `OtpMfaSetupRequest` (same fields as above). Returns `Response`. ```graphql mutation { sms_otp_mfa_setup(params: { phone_number: "+10000000000" }) { message } } ``` #### `verify_totp` Completes an in-progress, token-withheld MFA first-time-setup offer by recording that the caller explicitly declined it, then issues the access token that was withheld (see [Withheld-token first-time setup](../core/security#withheld-token-first-time-setup)). Accepts `params` of type `SkipMfaSetupRequest`. **Request Params** | Key | Description | Required | | -------------- | ------------------------------------------------------------- | -------- | | `email` | Email address of the user (resolves the pending MFA session) | false | | `phone_number` | Phone number of the user (resolves the pending MFA session) | false | | `state` | Authorization-code-grant state, same as `verify_otp` | false | Either `email` or `phone_number` is required. Returns `AuthResponse` (same shape as [`verify_otp`](#verify_otp)). Fails with an error when MFA is org-enforced (`--enforce-mfa`) — enforcement is never skippable. This call is authenticated by the MFA session, not a bearer token — none has been issued yet. The session arrives in a `Set-Cookie` header on the `signup`/`login` response and goes back in a `Cookie` header here, so **any HTTP client can complete the flow**, not only a browser. See [Completing the flow from a non-browser client](../core/security#completing-the-flow-from-a-non-browser-client). ```graphql mutation { skip_mfa_setup(params: { email: "foo@bar.com" }) { access_token expires_in message } } ``` #### `lock_mfa` Records that the caller lost access to their only enrolled MFA factor(s), permanently locking the account until an admin recovers it (see [Lockout & admin recovery](../core/security#lockout--admin-recovery)). Only allowed when the caller has no verified email/SMS OTP fallback enrolled — use that instead of locking if one exists. Does **not** issue a token. Accepts `params` of type `LockMfaRequest`. **Request Params** | Key | Description | Required | | -------------- | ----------------------- | -------- | | `email` | Email address of the user | false | | `phone_number` | Phone number of the user | false | Either `email` or `phone_number` is required. Returns `Response`. ```graphql mutation { lock_mfa(params: { email: "foo@bar.com" }) { message } } ``` #### `email_otp_mfa_setup` Sends a one-time code to the caller's own email and creates an unverified email-OTP MFA enrollment; verify it with [`verify_otp`](#verify_otp) to activate. Accepts `params` of type `OtpMfaSetupRequest`. Dual-mode: with a valid bearer token/session, `params` is ignored and the code goes to the already-authenticated caller (the settings-screen "add a second factor" flow); without one, `email`/`phone_number` resolve the pending MFA session cookie (the withheld first-time-setup flow). **Request Params** | Key | Description | Required | | -------------- | -------------------------------------------------------------------- | -------- | | `email` | Email address (MFA-session-cookie mode only; ignored when bearer-authenticated) | false | | `phone_number` | Phone number (MFA-session-cookie mode only; ignored when bearer-authenticated) | false | Returns `Response`. ```graphql mutation { email_otp_mfa_setup(params: { email: "foo@bar.com" }) { message } } ``` #### `sms_otp_mfa_setup` Sends a one-time code to the caller's own phone number and creates an unverified SMS-OTP MFA enrollment. Same dual-mode permissions and `verify_otp` activation relationship as [`email_otp_mfa_setup`](#email_otp_mfa_setup). Accepts `params` of type `OtpMfaSetupRequest` (same fields as above). Returns `Response`. ```graphql mutation { sms_otp_mfa_setup(params: { phone_number: "+10000000000" }) { message } } ``` #### `totp_mfa_setup` Generates a fresh TOTP secret, QR image, and recovery codes for the caller to enroll as an MFA method — the TOTP twin of [`email_otp_mfa_setup`](#email_otp_mfa_setup) / [`sms_otp_mfa_setup`](#sms_otp_mfa_setup). Unlike those, nothing is sent anywhere: the enrollment payload comes back directly, so the caller scans or enters it, then completes enrollment via [`verify_otp`](#verify_otp) with `is_totp: true`. Same dual-mode permissions as the other setup mutations: an already-authenticated caller adding a second factor, or a caller in the withheld first-time MFA-offer state identified by the MFA session cookie. Accepts `params` of type `OtpMfaSetupRequest`. Returns `AuthResponse`. ```graphql mutation { totp_mfa_setup { message should_show_totp_screen authenticator_scanner_image authenticator_secret authenticator_recovery_codes } } ``` #### `webauthn_registration_options` Returns the WebAuthn creation options (an opaque JSON string) to pass to the browser's `navigator.credentials.create()`. Takes optional top-level `email` / `phone_number` scalars rather than a `params` object. Returns `WebauthnRegistrationOptionsResponse` (`{ options }`). #### `webauthn_registration_verify` Submits the credential the browser produced to finish registering a passkey. Accepts `params` of type `WebauthnRegistrationVerifyRequest`. Returns `AuthResponse`: on the MFA-session-cookie path this also completes the gate and issues the withheld access token; on the ordinary authenticated path `access_token` is null. #### `webauthn_login_options` Returns the WebAuthn request options for `navigator.credentials.get()`. Omit `email` for the usernameless (discoverable credential) ceremony. Returns `WebauthnLoginOptionsResponse` (`{ options }`). #### `webauthn_login_verify` Submits the signed assertion to complete passkey login. Accepts `params` of type `WebauthnLoginVerifyRequest`. Returns `AuthResponse` with tokens. #### `webauthn_credentials` Lists the authenticated caller's own registered passkeys. Returns `[WebauthnCredentialInfo!]!`. Requires authentication. #### `webauthn_delete_credential` Deletes one of the authenticated caller's own passkeys by `id`. Returns `Response`. Requires authentication. #### `verify_totp` Generates a fresh TOTP secret, QR image, and recovery codes for the caller to enroll as an MFA method — the TOTP twin of [`email_otp_mfa_setup`](#email_otp_mfa_setup) / [`sms_otp_mfa_setup`](#sms_otp_mfa_setup). Unlike those, nothing is sent anywhere: the enrollment payload comes back directly, so the caller scans or enters it, then completes enrollment via [`verify_otp`](#verify_otp) with `is_totp: true`. Same dual-mode permissions as the other setup mutations: an already-authenticated caller adding a second factor, or a caller in the withheld first-time MFA-offer state identified by the MFA session cookie. Accepts `params` of type `OtpMfaSetupRequest`. Returns `AuthResponse`. ```graphql mutation { totp_mfa_setup { message should_show_totp_screen authenticator_scanner_image authenticator_secret authenticator_recovery_codes } } ``` #### `webauthn_registration_options` Returns the WebAuthn creation options (an opaque JSON string) to pass to the browser's `navigator.credentials.create()`. Takes optional top-level `email` / `phone_number` scalars rather than a `params` object. Returns `WebauthnRegistrationOptionsResponse` (`{ options }`). #### `webauthn_registration_verify` Submits the credential the browser produced to finish registering a passkey. Accepts `params` of type `WebauthnRegistrationVerifyRequest`. Returns `AuthResponse`: on the MFA-session-cookie path this also completes the gate and issues the withheld access token; on the ordinary authenticated path `access_token` is null. #### `webauthn_login_options` Returns the WebAuthn request options for `navigator.credentials.get()`. Omit `email` for the usernameless (discoverable credential) ceremony. Returns `WebauthnLoginOptionsResponse` (`{ options }`). #### `webauthn_login_verify` Submits the signed assertion to complete passkey login. Accepts `params` of type `WebauthnLoginVerifyRequest`. Returns `AuthResponse` with tokens. #### `webauthn_credentials` Lists the authenticated caller's own registered passkeys. Returns `[WebauthnCredentialInfo!]!`. Requires authentication. #### `webauthn_delete_credential` Deletes one of the authenticated caller's own passkeys by `id`. Returns `Response`. Requires authentication. #### Verifying TOTP {#verify_totp} There is no separate `verify_totp` mutation. TOTP codes go through [`verify_otp`](#verify_otp) with `is_totp: true` — the same mutation that verifies email and SMS codes, so one code path handles every second factor. **Request Params** (`VerifyOTPRequest`) | Key | Description | Required | |----------------|------------------------------------------------------|----------| | `email` | Email address of user | false | | `phone_number` | Phone number of user | false | | `otp` | Code from the authenticator app | true | | `is_totp` | Must be `true` for an authenticator code | true | | `state` | Authorization-code grant flow state | false | Either `email` or `phone_number` is required — it identifies which pending login this code belongs to. The same call completes enrollment after [`totp_mfa_setup`](#totp_mfa_setup). This mutation returns `AuthResponse` type with following keys **Response** | Key | Description | | ------------------------------- |---------------------------------------------------------------------------------------------------------------------------------------------------| | `message` | Success / Error message from server | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | | `user` | User object with its profile keys mentioned [above](#profile). | | `authenticator_recovery_codes` | Recovery codes, returned once when TOTP enrollment completes. | **Sample Mutation** ```graphql mutation { verify_otp(params: { email: "foo@bar.com", otp: "AB123C", is_totp: true }) { user { email given_name family_name picture roles } access_token expires_in message } } ``` #### `deactivate_account` Mutation to deactivate the user account `deactivate_account`. It returns `Response` type with the following keys. > Note: this is authorized route, so Authorization Header with bearer access token must be present or HTTPs cookie should be present. **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { deactivate_account { message } } ``` ### Authorizer Admin APIs All admin operations require super-admin authentication via either the `x-authorizer-admin-secret` header or the `authorizer.admin` HTTP-only session cookie (set by `_admin_login`). Except `_admin_login`, which may be called without an existing session. The same operations are also available over gRPC and REST through the `AuthorizerAdminService` (see the [gRPC](./grpc.md) and [REST](./rest-api.md) references). #### Admin Authentication ##### `_admin_login` Mutation to signup administrator. This only works if `ADMIN_SECRET` env is not set. It accepts `params` of type `AdminSignupInput` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. | Key | Description | Required | | -------------- | ---------------------------------- | -------- | | `admin_secret` | Secure secret with >= 6 characters | `true` | This mutation returns `Response` type with message **Sample Mutation** ```graphql mutation { _admin_signup(params: { admin_secret: "some string" }) { message } } ``` #### `_admin_login` Mutation to login administrator. It accepts `params` of type `AdminLoginInput` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. | Key | Description | Required | | -------------- | ---------------------------------- | -------- | | `admin_secret` | Secure secret with >= 6 characters | `true` | This mutation returns `Response` type with message **Sample Mutation** ```graphql mutation { _admin_login(params: { admin_secret: "some string" }) { message } } ``` ##### `_admin_logout` Mutation to logout administrator. It does not have any params > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. This mutation returns `Response` type with message **Sample Mutation** ```graphql mutation { _admin_logout { message } } ``` ##### `_admin_session` Query to get admin session for dashboard > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. ```json { "x-authorizer-admin-secret": "ADMIN_SECRET" } ``` | Key | Description | | --------- | ------------------------------------ | | `message` | Success response message from server | **Sample Query** ```graphql query { _admin_session { message } } ``` ##### `_admin_meta` Query to get admin metadata (server info available to admins). Returns all fields from `meta` plus admin-only fields. **Admin-only fields** | Key | Description | | ----------------------------------- | ---------------------------------------------------------- | | `is_multi_factor_auth_service_enabled` | Whether at least one MFA method is available (at least one method enabled and its provider configured) | **Sample Query** ```graphql query { _admin_meta { version client_id is_totp_mfa_enabled is_email_otp_mfa_enabled is_sms_otp_mfa_enabled is_multi_factor_auth_service_enabled } } ``` #### Users ##### `_users` Query to get all the `_users`. This query is only allowed for super admins. It returns array of users `Users` with below mentioned keys. > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer.admin` as http only cookie. ```json { "x-authorizer-admin-secret": "ADMIN_SECRET" } ``` It can take optional `params` input of type `ListUsersRequest` with following keys **Request Params** | Key | Description | Required | Default | | ------------ | ------------------------------------------------------------------------------------- | -------- | ------- | | `pagination` | Object with `page` and `limit` for pagination | false | page: 1, limit: 10 | | `query` | Case-insensitive substring filter (matches against user ID, email, given_name, family_name, nickname). Empty or absent means no filter. | false | empty | **Sample Query** ```graphql query { _users(params: { pagination: { page: 2 limit: 10 } }) { pagination { offset total page limit } users { id given_name family_name email picture roles } } } ``` ##### `_user` Query to get a specific user by either id or email. > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer.admin` as http only cookie. ```json { "x-authorizer-admin-secret": "ADMIN_SECRET" } ``` It requires either of following parameters **Request Param** | Key | Description | Required | | ------- | ---------------------- | -------- | | `id` | Identifier of the user | false | | `email` | User's email address | false | **Sample Query** ```graphql query { _user(params: { id: '123-123123-1231231' }) { id email } } ``` It returns the whole `User` object mentioned in [profile](#profile) query section #### `_update_user` Mutation to update the profile of users. This mutation is only allowed for super admins. It accepts `params` of type `UpdateUserInput` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. ```json { "x-authorizer-admin-secret": "ADMIN_SECRET" } ``` **Request Params** | Key | Description | Required | | -------------- | --------------------------------- | -------- | | `id` | ID of user to be updated | true | | `email` | New email address of user | false | | `given_name` | Updated first name of user | false | | `family_name` | Updated last name of user | false | | `picture` | Updated picture url of user | false | | `roles` | Set of new roles for a given user | false | | `middle_name` | New middle name of user | false | | `nickname` | New nick name of user | false | | `gender` | New gender of user | false | | `birthdate` | New birthdate of user | false | | `phone_number` | New phone number of user | false | This mutation returns `User` type with update values **Sample Mutation** ```graphql mutation { _update_user( params: { id: "20", given_name: "Bob", roles: ["user", "admin"] } ) { id given_name roles createdAt updatedAt } } ``` ##### `_delete_user` Mutation to delete user. This mutation is only allowed for super admins. It accepts `params` of type `DeleteUserRequest` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. **Request Params** | Key | Description | Required | | ---- | ------------------------------------------------- | -------- | | `id` | ID of user that needs to be removed from platform | true | :::warning Breaking in 2.4.0 This took `email` and now takes `id` only. Email is not an identifier every account has — a phone-only signup has none — so an email-keyed delete could not reach those accounts at all, and there was no second identifier accepted. Pass the `id` you already have from `_users` or `_user`. ::: This mutation returns `Response` type with following keys **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { _delete_user(params: { email: "foo@bar.com" }) { message } } ``` ##### `_verification_requests` Query to get all the `_verification_requests`. This query is only allowed for super admins. It returns array of verification requests `[VerificationRequest!]!` with following keys. > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. ```json { "x-authorizer-admin-secret": "ADMIN_SECRET" } ``` It can take optional `params` input of type `PaginatedInput` with following keys **Request Params** | Key | Description | Required | Default | | ------- | ---------------------------- | -------- | ------- | | `page` | Number of page that you want | false | 1 | | `limit` | Number of rows that you want | false | 10 | **Sample Query** ```graphql query { _verification_requests(params: { limit: 10, page: 2 }) { pagination { limit offset page } verification_requests { id token email expires identifier } } } ``` #### Access Control ##### `_revoke_access` Mutation to revoke access of a given user. This mutation is only allowed for super admins. It accepts `params` of type `UpdateAccessInput` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. **Request Params** | Key | Description | Required | | --------- | ---------------------------------------- | -------- | | `user_id` | Id of user whose access is to be revoked | true | This mutation returns `Response` type with following keys **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { _revoke_access(params: { user_id: "test" }) { message } } ``` ##### `_enable_access` Mutation to enable access of a given user whose access revoked earlier. This mutation is only allowed for super admins. It accepts `params` of type `UpdateAccessInput` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. **Request Params** | Key | Description | Required | | --------- | ---------------------------------------- | -------- | | `user_id` | Id of user whose access is to be enabled | true | This mutation returns `Response` type with following keys **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { _enable_access(params: { user_id: "test" }) { message } } ``` ##### `_invite_members` Mutation to invite members. This mutation is only allowed for super admins. It accepts `params` of type `InviteMemberInput` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. **Request Params** | Key | Description | Required | | -------------- | ---------------------------------------------------------------------------------------------------------- | -------- | | `emails` | List of emails that needs to be invited on platform | true | | `redirect_uri` | URI to which user should be redirected when they click on invitation link. Defaults to authorizer app page | false | This mutation returns `Response` type with following keys **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { _invite_members(params: { emails: ["foo@yopmail.com"] }) { message } } ``` #### Webhooks ##### `_test_endpoint` Mutation to test webhook endpoint. This mutation is allowed for admins only. It accepts `params` of type `TestEndpointRequest` with following keys and returns `TestEndpointResponse` > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. **Request Params** | Key | Description | Required | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `event_name` | Name of event for which webhook should be called. Currently, supports `user.login`, `user.created`, `user.signup`, `user.access_revoked`, `user.access_enabled`, `user.deleted`, `user.deactivated`, `user.provisioned`, `user.deprovisioned`, `user.scim_updated`, `group.created`, `group.updated`, `group.deleted`, `user.approval_requested` ([CIBA](../enterprise/ciba)) events only. This is a unique field, means you can have one webhook for each event. | `true` | | `endpoint` | Endpoint that needs to be called for a given event | `true` | | `headers` | JSON of key, value pair which are extra HTTP headers to be sent. Default header added is `content-type: application/json` | `false` | It sends following data to your webhook with `POST` method ```json { "event_name": "user.login", "user": {}, "auth_recipe": "basic_auth" } ``` **Response** | Key | Description | | ------------- | --------------------------------------------- | | `http_status` | HTTP status integer from the webhook endpoint | | `response` | JSON response sent by webhook | **Sample Mutation** ```graphql mutation { _test_endpoint(params: { event_name: "user.login", endpoint: "https://foo.com/webhook", headers: {"Authorization": "Basic test"} }) { http_status response } } ``` ##### `_add_webhook` Mutation to add webhook. This mutation is allowed for admins only. It accepts `params` of type `AddWebhookRequest` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. **Request Params** | Key | Description | Required | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `event_name` | Name of event for which webhook should be called. Currently, supports `user.login`, `user.created`, `user.signup`, `user.access_revoked`, `user.access_enabled`, `user.deleted`, `user.deactivated`, `user.provisioned`, `user.deprovisioned`, `user.scim_updated`, `group.created`, `group.updated`, `group.deleted`, `user.approval_requested` ([CIBA](../enterprise/ciba)) events only. This is a unique field, means you can have one webhook for each event. | `true` | | `endpoint` | Endpoint that needs to be called for a given event | `true` | | `enabled` | Boolean to state if the webhook is enabled or disabled | `true` | | `headers` | JSON of key, value pair which are extra HTTP headers to be sent. Default header added is `content-type: application/json` | `false` | It sends following data to your webhook with `POST` method ```json { "event_name": "user.login", "user": {}, "auth_recipe": "basic_auth" } ``` **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { _add_webhook(params: { event_name: "user.login", endpoint: "https://foo.com/webhook", enabled: true, headers: {"Authorization": "Basic test"} }) { message } } ``` ##### `_update_webhook` Mutation to update webhook. This mutation is allowed for admins only. It accepts `params` of type `UpdateWebhookRequest` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. **Request Params** | Key | Description | Required | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `id` | Identifier of the webhook | `true` | | `event_name` | Name of event for which webhook should be called. Currently, supports `user.login`, `user.created`, `user.signup`, `user.access_revoked`, `user.access_enabled`, `user.deleted`, `user.deactivated`, `user.provisioned`, `user.deprovisioned`, `user.scim_updated`, `group.created`, `group.updated`, `group.deleted`, `user.approval_requested` ([CIBA](../enterprise/ciba)) events only. This is a unique field, means you can have one webhook for each event. | `false` | | `endpoint` | Endpoint that needs to be called for a given event | `false` | | `enabled` | Boolean to state if the webhook is enabled or disabled | `false` | | `headers` | JSON of key, value pair which are extra HTTP headers to be sent. Default header added is `content-type: application/json` | `false` | **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { _update_webhook(params: { id: "123-adfa-123412-asdfasda", event_name: "user.login", endpoint: "https://foo.com/webhook", enabled: true, headers: {"Authorization": "Basic test"} }) { message } } ``` ##### `_delete_webhook` Mutation to delete webhook. This mutation is allowed for admins only. It accepts `params` of type `WebhookRequest` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. **Request Params** | Key | Description | Required | | ---- | ------------------------- | -------- | | `id` | Identifier of the webhook | `true` | **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { _delete_webhook(params: { id: "123-adfa-123412-asdfasda" }) { message } } ``` ##### `_webhook` Query to get webhook by its identifier. This query is allowed for admins only. It accepts `params` of type `WebhookRequest` with following keys and returns `Webhook` > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. **Request Params** | Key | Description | Required | | ---- | ------------------------- | -------- | | `id` | Identifier of the webhook | `true` | **Response** | Key | Description | | ------------ | -------------------------------------------------------------------------- | | `id` | Identifier of the webhook | | `event_name` | Event for which the webhook will be executed | | `endpoint` | Endpoint that is to be called | | `enabled` | Boolean to know if webhook is enabled or disabled | | `headers` | JSON key, value pair object with the set of headers to be sent for webhook | | `created_at` | Time at which the webhook entry was created | | `updated_at` | Time at which the webhook entry was updated | **Sample Query** ```graphql query { _webhook(params: { id: "123-adfa-123412-asdfasda" }) { id event_name } } ``` ##### `_webhooks` Query to get list of webhooks. This query is allowed for admins only. > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. It can take optional `params` input of type `PaginatedInput` with following keys **Request Params** | Key | Description | Required | Default | | ------- | ---------------------------- | -------- | ------- | | `page` | Number of page that you want | false | 1 | | `limit` | Number of rows that you want | false | 10 | **Response** It returns response of type `Webhooks` with following keys | Key | Description | | ---------- | ------------------------------------------------------- | | pagination | object with `limit`, `page`, `offset` & `total` value | | webhooks | List of webhook with params mentioned [here](#_webhook) | **Sample Query** ```graphql _webhooks(params: {limit: 10, page: 1}) { pagination { limit offset total } webhooks { id event_name endpoint } } ``` ##### `_webhook_logs` Query to get list of webhook logs. This query is allowed for admins only. > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. It can take optional `params` input of type `ListWebhookLogRequest` with following keys **Request Params** | Key | Description | Required | Default | | ------------ | ----------------------------------- | -------- | ---------------------- | | `pagination` | Pagination object with limit & page | false | `{limit: 10, page: 1}` | | `webhook_id` | Identifier for the webhook | false | null | **Response** It returns response of type `WebhookLogs` with following keys | Key | Description | | ------------ | ---------------------------------------------------------------------------------------------------------- | | pagination | object with `limit`, `page`, `offset` & `total` value | | webhook_logs | List of webhook log (`id`, `http_status`, `request`, `response`, `webhook_id`, `created_at`, `updated_at`) | **Sample Query** ```graphql _webhook_logs(params: { pagination: { limit: 10 } webhook_id: "test" }) { pagination { limit offset total } webhook_logs { id http_status request response webhook_id } } ``` #### Email Templates ##### `_add_email_template` Mutation to add email template that will be used while sending emails. This mutation is allowed for admins only. It accepts `params` of type `AddEmailTemplateRequest` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. **Request Params** | Key | Description | Required | | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `event_name` | Name of event for which email template should be called. Currently, supports `basic_auth_signup`, `magic_link_login`, `update_email`, `forgot_password` events only. This is a unique field, means you can have one template for each event. | `true` | | `subject` | Subject line for the email | `true` | | `template` | HTML template that will be used while sending emails | `true` | **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { _add_email_template( params: { event_name: "basic_auth_signup", subject: "Welcome!", template: "hello world" } ) { message } } ``` ##### `_update_email_template` Mutation to update email template. This mutation is allowed for admins only. It accepts `params` of type `UpdateEmailTemplateRequest` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. **Request Params** | Key | Description | Required | | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `id` | Identifier of the email template | `true` | | `event_name` | Name of event for which email template should be called. Currently, supports `basic_auth_signup`, `magic_link_login`, `update_email`, `forgot_password` events only. This is a unique field, means you can have one template for each event. | `false` | | `subject` | Subject line for the email | `false` | | `template` | HTML template that will be used while sending emails | `false` | **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { _update_email_template( params: { id: "123-adfa-123412-asdfasda" event_name: "update_email" template: "Welcome back!" } ) { message } } ``` ##### `_delete_email_template` Mutation to delete email template. This mutation is allowed for admins only. It accepts `params` of type `DeleteEmailTemplateRequest` with following keys > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. **Request Params** | Key | Description | Required | | ---- | -------------------------------- | -------- | | `id` | Identifier of the email template | `true` | **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Mutation** ```graphql mutation { _delete_email_template(params: { id: "123-adfa-123412-asdfasda" }) { message } } ``` ##### `_email_templates` Query to get list of email templates. This query is allowed for admins only. > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. It can take optional `params` input of type `PaginatedInput` with following keys **Request Params** | Key | Description | Required | Default | | ------- | ---------------------------- | -------- | ------- | | `page` | Number of page that you want | false | 1 | | `limit` | Number of rows that you want | false | 10 | **Response** It returns response of type `EmailTemplates` with following keys | Key | Description | | --------------- | ----------------------------------------------------- | | pagination | object with `limit`, `page`, `offset` & `total` value | | email_templates | List of email template | **Sample Query** ```graphql _email_templates(params: {limit: 10, page: 1}) { pagination { limit offset total } email_templates { id template event_name created_at updated_at } } ``` #### Audit Logs ##### `_audit_logs` Query to get a paginated list of audit log entries. This query is allowed for admins only. > Note: the super admin query can be access via special header with super admin secret (this is set via ENV) or `authorizer-admin` as http only cookie. It can take optional `params` input with pagination and filtering options. **Request Params** | Key | Description | Required | Default | | ---------------- | ----------------------------------- | -------- | ------- | | `page` | Number of page that you want | false | 1 | | `limit` | Number of rows that you want | false | 10 | | `actor_id` | Filter by actor ID | false | null | | `action` | Filter by action | false | null | | `resource_type` | Filter by resource type | false | null | | `resource_id` | Filter by resource id | false | null | | `from_timestamp` | Filter entries at/after this Unix timestamp | false | null | | `to_timestamp` | Filter entries at/before this Unix timestamp | false | null | Filters combine with AND. Every filter above is applied by every supported database backend. > **Before v2.4.2** ([#802](https://github.com/authorizerdev/authorizer/pull/802)), > CassandraDB/ScyllaDB and Couchbase applied only `actor_id` and `action`. The > other four filters were accepted and **silently ignored**, so a query narrowed > to one resource or one time window returned unfiltered rows, with no error to > indicate it. On ScyllaDB, combining two filters failed outright. If you are > upgrading from an earlier version on one of those backends, expect result > counts and `pagination.total` to drop: the filters now do what this table > always said they did. > See [Databases](./databases) for the index-backfill caveat on those backends. **Sample Query** ```graphql query { _audit_logs(params: { pagination: { limit: 10, page: 1 }, actor_id: "user-123" }) { pagination { limit offset page total } audit_logs { id actor_id action resource_type resource_id created_at } } } ``` #### Authorization (FGA) Manage the embedded FGA (ReBAC) engine: the authorization model and the relationship tuples. All require super-admin authentication (cookie or `X-Authorizer-Admin-Secret`). All admin authorization operations are namespaced with the `_fga_` prefix. See [Authorization (FGA)](./authorization) for the conceptual model. ##### `_fga_write_model` Install a new authorization-model version from an FGA DSL string and make it active. Models are append-only — earlier versions are retained. Returns `FgaModel` `{ id, dsl }`. ```graphql mutation { _fga_write_model(params: { dsl: """ model schema 1.1 type user type document relations define viewer: [user] define editor: [user] """ }) { id dsl } } ``` ##### `_fga_get_model` Read the current authorization model. Returns `FgaModel` `{ id, dsl }`. ```graphql query { _fga_get_model { id dsl } } ``` ##### `_fga_write_tuples` Write relationship tuples. Returns `Response` `{ message }`. Input `params.tuples` is `[FgaTupleInput!]!`, each `{ user: String!, relation: String!, object: String! }`. ```graphql mutation { _fga_write_tuples(params: { tuples: [ { user: "user:1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", relation: "viewer", object: "document:1" } ] }) { message } } ``` ##### `_fga_delete_tuples` Delete relationship tuples. Same input shape as `_fga_write_tuples`. Returns `Response` `{ message }`. ```graphql mutation { _fga_delete_tuples(params: { tuples: [ { user: "user:1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", relation: "viewer", object: "document:1" } ] }) { message } } ``` ##### `_fga_read_tuples` Read stored tuples with pagination and optional filters. Any empty filter field acts as a wildcard for that position. Returns `FgaTuples` `{ tuples { user relation object }, continuation_token }` — `continuation_token` is empty when the result set is exhausted. Input `params` (`FgaReadTuplesInput`): | Key | Description | Required | | -------------------- | ------------------------------------------------ | -------- | | `user` | Filter by subject (e.g. `user:1b9d…`). Empty = any user. | `false` | | `relation` | Filter by relation (e.g. `viewer`). Empty = any relation. | `false` | | `object` | Filter by object (e.g. `document:1`). Empty = any object. | `false` | | `page_size` | Maximum number of tuples to return. | `false` | | `continuation_token` | Token from a previous response to fetch the next page. | `false` | ```graphql query { _fga_read_tuples(params: { object: "document:1", page_size: 50 }) { tuples { user relation object } continuation_token } } ``` ##### `_fga_list_users` List the users that have a given relation on an object (admin only — reveals the access graph). Returns `{ users }` — fully-qualified user ids (e.g. `"user:1b9d…"`). Input `params` (`FgaListUsersInput`): | Key | Description | Required | | ----------- | ------------------------------------------------------ | -------- | | `object` | Object to inspect (e.g. `document:1`). | `true` | | `relation` | Relation to resolve (e.g. `viewer`). | `true` | | `user_type` | Type of subjects to enumerate (e.g. `user`). | `true` | ```graphql query { _fga_list_users(params: { object: "document:1", relation: "viewer", user_type: "user" }) { users } } ``` ##### `_fga_expand` Expand the relationship/userset tree for a relation on an object (admin only — reveals the access graph). Useful for debugging how access is derived. Returns `{ tree }` — the [OpenFGA](https://openfga.dev) userset tree serialized as a JSON string. Input `params` (`FgaExpandInput`): `{ relation: String!, object: String! }`. ```graphql query { _fga_expand(params: { relation: "viewer", object: "document:1" }) { tree } } ``` ##### `_fga_reset` Delete the authorization model, all of its versions, and all tuples. Returns `Response` `{ message }`. The operation is refused while any tuple still exists, so delete tuples first. ```graphql mutation { _fga_reset { message } } ``` --- ## gRPC API Authorizer exposes its service over native **gRPC**, alongside the [GraphQL](./graphql-api) and [REST](./rest-api) surfaces. All three are backed by the same service layer and the same Protocol Buffers definition, so they behave identically — gRPC just gives you a strongly-typed, high-performance binary transport for server-to-server calls. Table of Contents - [Service & transport](#service--transport) - [Protobuf schema](#protobuf-schema) - [Public Methods](#public-methods) - [`Meta`](#meta) - [`Signup`](#signup) - [`Login`](#login) - [`MagicLinkLogin`](#magiclinklogin) - [`VerifyEmail`](#verifyemail) - [`ResendVerifyEmail`](#resendverifyemail) - [`VerifyOtp`](#verifyotp) - [`ResendOtp`](#resendotp) - [`SkipMfaSetup`](#skipmfasetup) - [`LockMfa`](#lockmfa) - [`EmailOtpMfaSetup`](#emailotpmfasetup) - [`SmsOtpMfaSetup`](#smsotpmfasetup) - [`ForgotPassword`](#forgotpassword) - [`ResetPassword`](#resetpassword) - [`Session`](#session) - [`Profile`](#profile) - [`UpdateProfile`](#updateprofile) - [`DeactivateAccount`](#deactivateaccount) - [`Logout`](#logout) - [`Revoke`](#revoke) - [`ValidateJwtToken`](#validatejwttoken) - [`ValidateSession`](#validatesession) - [`CheckPermissions`](#checkpermissions) - [`ListPermissions`](#listpermissions) - [Authorizer Admin Methods](#authorizer-admin-methods) - [Admin Authentication](#admin-authentication) - [`AdminLogin`](#adminlogin) - [`AdminLogout`](#adminlogout) - [`AdminSession`](#adminsession) - [`AdminMeta`](#adminmeta) - [User Management](#user-management) - [`Users`](#users) - [`User`](#user) - [`UpdateUser`](#updateuser) - [`DeleteUser`](#deleteuser) - [`VerificationRequests`](#verificationrequests) - [Access Control](#access-control) - [`RevokeAccess`](#revokeaccess) - [`EnableAccess`](#enableaccess) - [`InviteMembers`](#invitemembers) - [Webhook Management](#webhook-management) - [`AddWebhook`](#addwebhook) - [`UpdateWebhook`](#updatewebhook) - [`DeleteWebhook`](#deletewebhook) - [`GetWebhook`](#getwebhook) - [`Webhooks`](#webhooks) - [`WebhookLogs`](#webhooklogs) - [`TestEndpoint`](#testendpoint) - [Email Template Management](#email-template-management) - [`AddEmailTemplate`](#addemailtemplate) - [`UpdateEmailTemplate`](#updateemailtemplate) - [`DeleteEmailTemplate`](#deleteemailtemplate) - [`EmailTemplates`](#emailtemplates) - [Audit Logs](#audit-logs) - [`AuditLogs`](#auditlogs) - [Authorization (FGA)](#authorization-fga) - [`FgaGetModel`](#fgagetmodel) - [`FgaWriteModel`](#fgawritemodel) - [`FgaWriteTuples`](#fgawritetuples) - [`FgaDeleteTuples`](#fgadeletetuples) - [`FgaReadTuples`](#fgaread-tuples) - [`FgaListUsers`](#fgalistusers) - [`FgaExpand`](#fgaexpand) - [`FgaReset`](#fgareset) - [Client Registry](#client-registry) - [`CreateClient`](#createclient) - [`UpdateClient`](#updateclient) - [`DeleteClient`](#deleteclient) - [`RotateClientSecret`](#rotateclientsecret) - [`GetClient`](#getclient) - [`Clients`](#clients) - [Trusted Issuers](#trusted-issuers) - [`AddTrustedIssuer`](#addtrustedissuer) - [`UpdateTrustedIssuer`](#updatetrustedissuer) - [`DeleteTrustedIssuer`](#deletetrustedissuer) - [`GetTrustedIssuer`](#gettrustedissuer) - [`TrustedIssuers`](#trustedissuers) - [SAML IdP](#saml-idp) - [`CreateSamlServiceProvider`](#createsamlserviceprovider) - [`UpdateSamlServiceProvider`](#updatesamlserviceprovider) - [`DeleteSamlServiceProvider`](#deletesamlserviceprovider) - [`GetSamlServiceProvider`](#getsamlserviceprovider) - [`ListSamlServiceProviders`](#listsamlserviceproviders) - [`RotateSamlIdpCert`](#rotatesamlidpcert) - [`RetireSamlIdpKey`](#retiresamlidpkey) - [`ListSamlIdpKeys`](#listsamlidpkeys) - [`ImportSamlSpMetadata`](#importsamlspmetadata) - [Calling with `grpcurl`](#calling-with-grpcurl) - [Health checks](#health-checks) - [Errors](#errors) - [See also](#see-also) ### Service & transport | Property | Value | | --------------------- | ------------------------------------------------------------------ | | Proto package | `authorizer.v1` | | Services | `AuthorizerService` (public) + `AuthorizerAdminService` (admin) | | BSR module | [`buf.build/authorizerdev/authorizer`](https://buf.build/authorizerdev/authorizer) | | Port | `--grpc-port` (default `9091`) — same server, both services | | TLS | `--grpc-tls-cert` + `--grpc-tls-key`; `--grpc-insecure` for dev | | Server reflection | `--enable-grpc-reflection` (default `true`) | | Health checking | `grpc.health.v1.Health` (always registered) | | JSON field casing (REST)| `snake_case` via `UseProtoNames` — payloads match GraphQL byte-for-byte | The gRPC server is enabled by default. Auth flows over gRPC exactly as they do over REST: attach the user's credential as request metadata — `authorization: Bearer ` — or forward the `cookie` header from a browser session. #### Session cookies over gRPC and REST Cookie-setting flows (`Signup`, `Login`, `Session`, `VerifyEmail`, `VerifyOtp`, and MFA challenge paths) emit session/MFA cookies as `set-cookie` **gRPC response metadata**. Over native gRPC, clients that need cookie-based auth must read these metadata headers and forward the `Cookie` value on subsequent calls. Over REST, the grpc-gateway promotes them to real `Set-Cookie` HTTP headers (previously they surfaced as `Grpc-Metadata-Set-Cookie`, which browsers ignored). | Cookie | gRPC metadata / REST header | Set by | | ------ | --------------------------- | ------ | | App session (`cookie_session`, `cookie_session_domain`) | `set-cookie` → `Set-Cookie` | `Signup`, `Login`, `Session`, `VerifyEmail`, `VerifyOtp` | | MFA challenge (`mfa`) | `set-cookie` → `Set-Cookie` | `Login`, `ForgotPassword`, `ResendOtp` when MFA is required | | Admin session (`authorizer-admin`) | `set-cookie` → `Set-Cookie` | `AdminLogin`, `AdminSession` | Admin auth also accepts `x-authorizer-admin-secret` as incoming metadata (mirrored from the REST `X-Authorizer-Admin-Secret` header). ### Protobuf schema The schema is published to the **[Buf Schema Registry](https://buf.build/authorizerdev/authorizer)** as the module `buf.build/authorizerdev/authorizer` (all messages live in a single `authorizer.v1` package). You can generate a typed client for any language without copying `.proto` files around: ```yaml # buf.gen.yaml version: v2 inputs: - module: buf.build/authorizerdev/authorizer plugins: - remote: buf.build/grpc/go out: gen opt: paths=source_relative - remote: buf.build/protocolbuffers/go out: gen opt: paths=source_relative ``` ```bash buf generate ``` Swap the remote plugins for `buf.build/grpc/python`, `.../grpc/web`, etc. to target other languages. **Other options:** - **Vendor the source** — the `.proto` files live in the [`proto/` directory of the repo](https://github.com/authorizerdev/authorizer/tree/main/proto); run `buf generate` or `protoc` against them directly. - **No protos at all** — since [server reflection](#service--transport) is enabled by default, [`grpcurl`](#calling-with-grpcurl), Postman, etc. can call the API without any schema files. - **Skip codegen** — the official [Go](../sdks/authorizer-go/), [JavaScript](../sdks/authorizer-js/), and [Python](../sdks/authorizer-python/) SDKs wrap the API for you. ### Public Methods Each message mirrors its GraphQL/REST counterpart — see the linked [GraphQL API reference](./graphql-api) anchor for field-level details. > **Response types.** Methods return the bare domain message — there is no per-RPC wrapper. > `Signup`, `Login`, `VerifyEmail`, `VerifyOtp`, and `Session` return `AuthResponse`; > `Profile` returns `User`; `Meta` returns `Meta`. This keeps the gRPC, REST, and GraphQL > payloads identical (snake_case field names, no `auth` / `user` / `meta` envelope keys). > Request messages are likewise flat — send the RPC input fields directly. > > Example — `Login` returns a flat `AuthResponse` (not `{ "auth": { … } }`): > > ```json > { > "message": "Logged in successfully", > "access_token": "eyJhbGciOiJIUzI1NiIs…", > "expires_in": 1718534400, > "user": { "id": "…", "email": "jane@example.com" } > } > ``` #### `Meta` *Public.* Server feature flags & provider availability. Mirrors [`meta`](./graphql-api#meta). #### `Signup` *Public.* Register a new user. Mirrors [`signup`](./graphql-api#signup). #### `Login` *Public.* Authenticate with email/phone + password. Returns tokens, or an MFA challenge flag when OTP/[TOTP](https://datatracker.ietf.org/doc/html/rfc6238) is enabled. Mirrors [`login`](./graphql-api#login). #### `MagicLinkLogin` *Public.* Start a passwordless login; emails a magic link. Mirrors [`magic_link_login`](./graphql-api#magic_link_login). #### `VerifyEmail` *Public.* Complete email verification using the token from the verification email. Mirrors [`verify_email`](./graphql-api#verify_email). #### `ResendVerifyEmail` *Public.* Re-send the email-verification message. Mirrors [`resend_verify_email`](./graphql-api#resend_verify_email). #### `VerifyOtp` *Public.* Complete an MFA challenge by submitting the email/phone OTP. Mirrors [`verify_otp`](./graphql-api#verify_otp). #### `ResendOtp` *Public.* Re-send the MFA OTP. Mirrors [`resend_otp`](./graphql-api#resend_otp). #### `SkipMfaSetup` *Public.* Completes an in-progress, token-withheld MFA offer by recording an explicit decline, then issues the withheld access token. Fails with `FAILED_PRECONDITION` when MFA is org-enforced (`--enforce-mfa`). Mirrors [`skip_mfa_setup`](./graphql-api#skip_mfa_setup). #### `LockMfa` *Public.* Records that the caller lost access to their only MFA factor(s); only allowed with no verified Email/SMS OTP fallback enrolled. Does not issue a token — the account requires admin recovery afterward. Mirrors [`lock_mfa`](./graphql-api#lock_mfa). #### `EmailOtpMfaSetup` *Public (dual-mode).* Sends a one-time code to the caller's own email and creates an unverified email-OTP MFA enrollment — either for an already-authenticated caller adding a second factor, or a caller in the withheld first-time-offer state identified by the MFA session cookie. Mirrors [`email_otp_mfa_setup`](./graphql-api#email_otp_mfa_setup). #### `SmsOtpMfaSetup` *Public (dual-mode).* Same as `EmailOtpMfaSetup`, for SMS. Mirrors [`sms_otp_mfa_setup`](./graphql-api#sms_otp_mfa_setup). #### `ForgotPassword` *Public.* Start password reset; emails a reset link. Mirrors [`forgot_password`](./graphql-api#forgot_password). #### `ResetPassword` *Public.* Set a new password using the reset token. Mirrors [`reset_password`](./graphql-api#reset_password). #### `Session` *Authenticated.* Refresh / fetch the current session. Mirrors [`session`](./graphql-api#session). #### `Profile` *Authenticated.* The authenticated user's profile. Mirrors [`profile`](./graphql-api#profile). #### `UpdateProfile` *Authenticated.* Update the authenticated user's profile. Mirrors [`update_profile`](./graphql-api#update_profile). #### `DeactivateAccount` *Authenticated.* Deactivate (soft-delete) the authenticated user's account. Mirrors [`deactivate_account`](./graphql-api#deactivate_account). #### `Logout` *Authenticated.* Invalidate the current session. Mirrors [`logout`](./graphql-api#logout). #### `Revoke` *Public.* Revoke a refresh token. Mirrors [`revoke`](./graphql-api#revoke). #### `ValidateJwtToken` *Public.* Validate a JWT and optional required relations. Mirrors [`validate_jwt_token`](./graphql-api#validate_jwt_token). #### `ValidateSession` *Authenticated.* Validate a session cookie and required relations. Mirrors [`validate_session`](./graphql-api#validate_session). #### `CheckPermissions` *Authenticated.* Batch-evaluate FGA `(relation, object)` checks. Mirrors [`check_permissions`](./graphql-api#check_permissions). #### `ListPermissions` *Authenticated.* List objects/relations the subject can access. Mirrors [`list_permissions`](./graphql-api#list_permissions). ### Authorizer Admin Methods The `AuthorizerAdminService` is served on the same gRPC port and address as `AuthorizerService`. All admin methods require super-admin authentication via the `x-authorizer-admin-secret` request metadata (the admin secret configured with `--admin-secret`) or an `authorizer.admin` session cookie. Except `AdminLogin`, which does not require an existing session. #### Admin Authentication ##### `AdminLogin` *Public (for admin-secret).* Authenticate as super-admin with the admin secret. Returns an auth response with session token. ##### `AdminLogout` *Admin-only.* Invalidate the current admin session. ##### `AdminSession` *Admin-only.* Verify the current admin session is valid. ##### `AdminMeta` *Admin-only.* Get admin-level server metadata (version, feature flags with admin-only fields). #### User Management ##### `Users` *Admin-only.* List all users with pagination. Mirrors [`_users`](./graphql-api#_users). ##### `User` *Admin-only.* Get a specific user by id or email. Mirrors [`_user`](./graphql-api#_user). ##### `UpdateUser` *Admin-only.* Update user profile fields (email, roles, name, etc.). Mirrors [`_update_user`](./graphql-api#_update_user). ##### `DeleteUser` *Admin-only.* Delete a user by id and all associated OTP/verification data. Mirrors [`_delete_user`](./graphql-api#_delete_user). :::warning Breaking in 2.4.0 `DeleteUserRequest.email` (field 1) is removed and replaced by `id` (field 2). Field 1 is **reserved**, not reused: both are strings, so reusing the tag would let an old client's email decode silently as an id on a delete path. Reserving makes an old client fail loudly instead. ::: ##### `VerificationRequests` *Admin-only.* List pending verification requests with optional pagination. Mirrors [`_verification_requests`](./graphql-api#_verification_requests). #### Access Control ##### `RevokeAccess` *Admin-only.* Revoke a user's access (set revoked_timestamp) and fire the `user.access_revoked` webhook. Mirrors [`_revoke_access`](./graphql-api#_revoke_access). ##### `EnableAccess` *Admin-only.* Re-enable a previously revoked user (clear revoked_timestamp) and fire the `user.access_enabled` webhook. Mirrors [`_enable_access`](./graphql-api#_enable_access). ##### `InviteMembers` *Admin-only.* Invite users to the platform by email with an invitation link. Mirrors [`_invite_members`](./graphql-api#_invite_members). #### Webhook Management ##### `AddWebhook` *Admin-only.* Register a new webhook for an event. Mirrors [`_add_webhook`](./graphql-api#_add_webhook). ##### `UpdateWebhook` *Admin-only.* Update an existing webhook (endpoint, headers, enabled state, etc.). Mirrors [`_update_webhook`](./graphql-api#_update_webhook). ##### `DeleteWebhook` *Admin-only.* Delete a webhook by id. Mirrors [`_delete_webhook`](./graphql-api#_delete_webhook). ##### `GetWebhook` *Admin-only.* Get a webhook by id. Mirrors [`_webhook`](./graphql-api#_webhook). ##### `Webhooks` *Admin-only.* List all webhooks with pagination. Mirrors [`_webhooks`](./graphql-api#_webhooks). ##### `WebhookLogs` *Admin-only.* List webhook delivery logs with optional pagination and webhook_id filter. Mirrors [`_webhook_logs`](./graphql-api#_webhook_logs). ##### `TestEndpoint` *Admin-only.* Send a test webhook payload to an endpoint and return the HTTP response. Mirrors [`_test_endpoint`](./graphql-api#_test_endpoint). #### Email Template Management ##### `AddEmailTemplate` *Admin-only.* Create a new email template for an event. Mirrors [`_add_email_template`](./graphql-api#_add_email_template). ##### `UpdateEmailTemplate` *Admin-only.* Update an email template. Mirrors [`_update_email_template`](./graphql-api#_update_email_template). ##### `DeleteEmailTemplate` *Admin-only.* Delete an email template by id. Mirrors [`_delete_email_template`](./graphql-api#_delete_email_template). ##### `EmailTemplates` *Admin-only.* List email templates with pagination. Mirrors [`_email_templates`](./graphql-api#_email_templates). #### Audit Logs ##### `AuditLogs` *Admin-only.* Retrieve audit log entries with optional filtering by actor, action, or resource and pagination. Mirrors [`_audit_logs`](./graphql-api#_audit_logs). #### Authorization (FGA) Manage the embedded fine-grained authorization (FGA) engine. See [Authorization (FGA)](./authorization) for the conceptual model. ##### `FgaGetModel` *Admin-only.* Retrieve the active authorization model as FGA DSL. An empty store returns an empty model (not an error). ##### `FgaWriteModel` *Admin-only.* Install a new authorization model version from FGA DSL. Models are versioned and append-only. Audited. ##### `FgaWriteTuples` *Admin-only.* Write (persist) relationship tuples. Audited. ##### `FgaDeleteTuples` *Admin-only.* Delete relationship tuples. Audited. ##### `FgaReadTuples` {#fgaread-tuples} *Admin-only.* Read stored tuples with optional filtering by user, relation, or object and pagination. ##### `FgaListUsers` *Admin-only.* List fully-qualified user ids that have a relation on an object (reveals the access graph). ##### `FgaExpand` *Admin-only.* Expand the relationship/userset tree for a relation on an object (useful for debugging). ##### `FgaReset` *Admin-only.* Delete the entire fine-grained authorization store (model, all versions, and all tuples) and start fresh. Refused if any tuples still exist. Destructive and audited. #### Client Registry Manage machine/workload identity clients (`service_account` and similar client types). See the [Client Registry guide](./client-registry) for the conceptual model. ##### `CreateClient` *Admin-only.* Provision a new client and return the generated client secret exactly once. ##### `UpdateClient` *Admin-only.* Update a client's name, description, allowed scopes, or active state. Never touches the secret. ##### `DeleteClient` *Admin-only.* Delete a client by id, cascading to its trusted issuers. ##### `RotateClientSecret` *Admin-only.* Replace the stored client secret with a fresh one, returned exactly once. The old secret stops validating immediately. ##### `GetClient` *Admin-only.* Get a single client by id. The client secret is never surfaced. ##### `Clients` *Admin-only.* List clients with pagination. Client secrets are never surfaced. #### Trusted Issuers Manage external JWT issuers used for [RFC 7523](https://datatracker.ietf.org/doc/html/rfc7523) `private_key_jwt` client assertions. See [Workload Identity](../enterprise/workload-identity). ##### `AddTrustedIssuer` *Admin-only.* Register an external issuer for a client. `subject_claim` defaults to `sub` when omitted. ##### `UpdateTrustedIssuer` *Admin-only.* Update an issuer's name, JWKS URL, expected audience, active state, or [SPIFFE](https://spiffe.io) refresh hint. ##### `DeleteTrustedIssuer` *Admin-only.* Delete a trusted issuer by id. ##### `GetTrustedIssuer` *Admin-only.* Get a single trusted issuer by id. ##### `TrustedIssuers` *Admin-only.* List trusted issuers, optionally filtered by client id, with pagination. #### SAML IdP Manage Authorizer acting as a [SAML 2.0](https://www.oasis-open.org/standard/saml/) identity provider for downstream service providers, plus IdP signing-key rotation. See [SAML IdP](../enterprise/saml-idp). ##### `CreateSamlServiceProvider` *Admin-only.* Register a downstream SP that Authorizer issues signed assertions to. ##### `UpdateSamlServiceProvider` *Admin-only.* Update a downstream SP's name, endpoints, certificate, attribute mapping, or active state. ##### `DeleteSamlServiceProvider` *Admin-only.* Delete a downstream SP by id. ##### `GetSamlServiceProvider` *Admin-only.* Get a single downstream SP by id. ##### `ListSamlServiceProviders` *Admin-only.* List downstream SPs for an org. ##### `RotateSamlIdpCert` *Admin-only.* Generate a new current signing keypair for an org's SAML IdP, demoting the previous current key. ##### `RetireSamlIdpKey` *Admin-only.* Retire a published-but-not-signing SAML IdP key by id. ##### `ListSamlIdpKeys` *Admin-only.* List all SAML IdP signing keys for an org. ##### `ImportSamlSpMetadata` *Admin-only.* Parse pasted SP metadata XML and return fields to prefill a create call. Performs no remote fetch and creates no record. ### Calling with `grpcurl` With reflection enabled you can explore and call the service directly: ```bash # List services grpcurl -plaintext localhost:9091 list # Describe a method grpcurl -plaintext localhost:9091 describe authorizer.v1.AuthorizerService.Login # Login (public) — response is a flat AuthResponse; check -H for set-cookie metadata grpcurl -plaintext \ -d '{"email":"jane@example.com","password":"Test@123"}' \ localhost:9091 authorizer.v1.AuthorizerService/Login # Check permissions (authenticated) grpcurl -plaintext \ -H "authorization: Bearer $ACCESS_TOKEN" \ -d '{"checks":[{"relation":"can_view","object":"document:1"}]}' \ localhost:9091 authorizer.v1.AuthorizerService/CheckPermissions ``` ```json { "results": [ { "relation": "can_view", "object": "document:1", "allowed": true } ] } ``` Drop `-plaintext` and use the TLS material when `--grpc-tls-cert` / `--grpc-tls-key` are configured. ### Health checks The standard gRPC health-checking protocol is registered, so Kubernetes `grpc` liveness/ readiness probes work out of the box: ```yaml livenessProbe: grpc: port: 9091 ``` Or with `grpc-health-probe` / `grpcurl`: ```bash grpcurl -plaintext localhost:9091 grpc.health.v1.Health/Check # {"status": "SERVING"} ``` ### Errors gRPC returns standard status codes; the HTTP [REST gateway](./rest-api) maps these to HTTP statuses. Common cases: | Status | Meaning | | ----------------------- | ---------------------------------------------------- | | `UNAUTHENTICATED` | Missing or invalid credentials. | | `PERMISSION_DENIED` | Explicit `user` not permitted for the caller. | | `FAILED_PRECONDITION` | FGA not enabled (`--fga-store` unset). | | `INVALID_ARGUMENT` | Validation failure (e.g. `> 100` checks). | ### See also - [REST API](./rest-api) — the same operations as JSON over HTTP (`/v1`). - [GraphQL API](./graphql-api) — the full field-level reference and complete auth surface. - [MCP Server](./mcp) — exposing `check_permissions` / `list_permissions` to AI agents. --- ## Overview ## Authorizer Core Authorizer is developed using [Golang](https://golang.org/). Authorizer core comes with: - [GraphQL API](./graphql-api), [REST API](./rest-api), and [gRPC API](./grpc) - [Fine-grained authorization (FGA)](./authorization) — relationship-based access control - [MCP server](./mcp) for AI agents - Email and Password login - OAuth login - Forgot password - Update profile API - Web application with a login page, sign up page, and forgot-password page. These can save hundreds of hours. - Secure session management with [HTTP cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) ### APIs Authorizer exposes the same service over multiple transports, all backed by one schema: | API | Use it for | Reference | | --- | ---------- | --------- | | **GraphQL** (`/graphql`) | The complete, canonical surface — all auth flows, admin operations, and FGA. | [GraphQL API](./graphql-api) | | **REST** (`/v1`) | Simple JSON-over-HTTP for scripts and server-to-server calls. | [REST API](./rest-api) | | **gRPC** (`:9091`) | Strongly-typed, high-performance binary RPC. | [gRPC API](./grpc) | | **MCP** (`/mcp`) | Letting an LLM agent check permissions on a user's behalf. | [MCP Server](./mcp) | For authorization, see the [Authorization (FGA)](./authorization) model and the [FGA Guide](./fga-guide) cookbook. #### How Authorizer is secure? One can authorize users in two ways: 1. Using HTTP Only cookie 2. Using JWT bearer token as part of `Authorization` header On successful login, Authorizers server sends [HTTP cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) to the browser. Client applications can use `credentials: include` option in `fetch` for further authorization. Users don't need to save this cookie in [localStorage](https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector/Local_Storage_Session_Storage) or [sessionStorage](https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector/Local_Storage_Session_Storage). This helps us prevent [XSS](https://owasp.org/www-community/attacks/xss/) or [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) attack. Client applications can also save `access_token` received on successful login in memory and use it as JWT bearer token as `Authorization` header. ### Why Golang? - High performant - Uses [gin](https://github.com/gin-gonic/gin#gin-web-framework) web framework, with best [benchmarks](https://github.com/gin-gonic/gin#benchmarks) ### Why GraphQL API? - Isomorphic schema - Client applications can request the data that is only required - In the future, we can stitch with other schema and offer schema-based permissions and user graph > For relationship-based, schema-driven permissions today, see [Authorization (FGA)](./authorization). > **Note:** You can always use GraphQL API as a rest API with the appropriate request body --- ## MCP Server Authorizer ships a built-in [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server. It lets an LLM agent — Claude Desktop, Claude Code, Cursor, or any MCP-compatible host — call a **curated, read-only subset** of Authorizer's API as tools: identify the current user and answer fine-grained authorization questions on their behalf. The headline use case: give an AI assistant the ability to ask *"is this user allowed to see this document?"* before it retrieves or summarizes content — the same permission-aware RAG pattern as the [`with-rag-fga`](https://github.com/authorizerdev/examples/tree/main/with-rag-fga) example (see [Real-world recipes → Permission-aware retrieval](./authorization#permission-aware-retrieval-rag--ai-agents)), but driven from inside the model instead of your backend. ### The MCP endpoint The MCP server is part of the Authorizer server you already run. There is nothing separate to install or start: turn it on with `--mcp-enabled` and clients connect to `POST /mcp` over Streamable HTTP, each with its own token. ```sh authorizer --url https://auth.example.com --mcp-enabled # ...your other flags ``` `--url` is already required to start the server at all; with `--mcp-enabled` it must also be a usable `http(s)` origin, and startup refuses anything else (no scheme, userinfo, a non-http scheme). Every token presented at `/mcp` is checked against this deployment's canonical resource identifier, `/mcp` — scheme + host only, with any path, query or trailing slash stripped. Without `--url` that identifier would be derived from request headers, which would let a caller name the audience their own token has to match — no check at all. #### Security model - **Every request carries its own token.** No ambient authority, no shared credential. - **Audience-bound tokens only.** A token is accepted at `/mcp` only when its `aud` is exactly `/mcp`. An ordinary login token — the kind that works at `/graphql`, `/v1/*` and gRPC — is rejected here, and an MCP token is rejected there. Neither rule has an "or" in it: a token you hand to a semi-trusted agent cannot become a full API credential. The mapping from audience to surface is a bijection, and that holds for [delegated tokens](#agent-delegation-rfc-8693) too. - **Bearer only.** No cookie, no admin secret, and no admin operation reaches this surface, so it is safe to expose to the public internet and exempt from CSRF. - **Shared middleware.** Because it is mounted on the main listener, it inherits CORS, security headers, rate limiting, trusted-proxy handling, request logging and metrics. #### Discovery Authorizer is both the authorization server and the resource server here, so a client needs nothing configured beyond the URL: 1. The client calls `POST https://auth.example.com/mcp` with no token. 2. Authorizer answers `401` with `WWW-Authenticate: Bearer realm="authorizer", resource_metadata="https://auth.example.com/.well-known/oauth-protected-resource/mcp"`. 3. The client fetches that document ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)): ```json { "resource": "https://auth.example.com/mcp", "authorization_servers": ["https://auth.example.com"], "bearer_methods_supported": ["header"], "scopes_supported": ["openid", "email", "profile", "phone", "offline_access"], "jwks_uri": "https://auth.example.com/.well-known/jwks.json", "resource_documentation": "https://docs.authorizer.dev/core/mcp" } ``` 4. It reads Authorizer's own metadata from `/.well-known/oauth-authorization-server`, runs the OAuth 2.1 authorization-code flow with PKCE, and passes `resource=https://auth.example.com/mcp` on both the authorization and token requests ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707)) so the issued token is bound to this server. That `resource` value must match **exactly** what a user types when adding the connector, including the path — give them `https://auth.example.com/mcp`, not the bare origin. An expired token gets the same `401`, which is what tells a client to refresh rather than retry. The audience binding survives refresh, so a rotated token keeps working. #### Connecting a client **Verified against a real Claude Code client**, so this table says what actually happens rather than what the specs allow. | Client | Works | How | | --- | --- | --- | | **Claude Code, VS Code** — static token | **yes, verified** | Mint a token bound to `/mcp` and pass it as a fixed header (below) | | **Claude Code** — [delegated token](#agent-delegation-rfc-8693) | **yes, verified** | Same fixed-header setup, with an RFC 8693 token bound to `/mcp`. Verified on Claude Code 2.1.233: `✔ Connected`, and a `check_permissions` tool call returned the agent's own intersected answer | | **Claude Code** — OAuth | **yes, verified** with `--enable-client-id-metadata-document` | Claude Code 2.1.333 identifies itself with the CIMD client id `https://claude.ai/oauth/claude-code-client-metadata`. The full flow was verified on 2.5.0: `claude mcp login` → Authorizer sign-in → the *Authorize Claude Code* consent screen → `✔ Connected`, followed by `profile` and `check_permissions` tool calls. With neither CIMD nor DCR enabled, it reports *does not support dynamic client registration*. Older releases (2.1.226) ignored CIMD and need `--enable-dynamic-client-registration` | | **Claude.ai custom connector** — pasted client ID | unverified | Anthropic documents an OAuth Client ID field under *Advanced settings*; not confirmed here | | Any client that needs to self-register | yes | Enable `--enable-client-id-metadata-document` (preferred) or `--enable-dynamic-client-registration` (RFC 7591, for clients that predate CIMD) | Both self-registration mechanisms ship in 2.4.0 and are **off by default**. Turn on the one your client can use — see [Self-registering clients](#self-registering-clients-cimd-vs-dcr) below. The static-token path remains the simplest option when you control the client and do not want an interactive flow at all. ```sh # 1. Create a service account: dashboard → Identity → Clients (note the id + secret) # 2. Mint a token bound to the MCP resource curl -s -X POST https://auth.example.com/oauth/token \ -d grant_type=client_credentials \ -d client_id=$CLIENT_ID -d client_secret=$CLIENT_SECRET \ -d scope=openid \ -d resource=https://auth.example.com/mcp # 3. Register it claude mcp add --transport http authorizer https://auth.example.com/mcp \ --header "Authorization: Bearer $ACCESS_TOKEN" ``` `claude mcp list` should then report **✔ Connected**. The `resource` parameter is the part people miss: without it the token's audience is the client id, and `/mcp` rejects it. That is the audience binding working, not a bug. Note this token identifies the *service account*, not a human — `profile` returns nothing useful and permission checks resolve to `service_account:`. For per-user identity use the OAuth flow with a self-registering client — see [CIMD](#connecting-a-client-that-self-registers-cimd) and [CIMD vs DCR](#self-registering-clients-cimd-vs-dcr) below (2.4.0+). #### Connecting a client that self-registers (CIMD) Set `--enable-client-id-metadata-document` alongside `--mcp-enabled` and a client can identify itself with an HTTPS URL pointing at a JSON document, instead of a `client_id` you registered in advance: ```json { "client_id": "https://app.example.com/oauth/client.json", "client_name": "Example MCP Client", "redirect_uris": ["http://127.0.0.1:0/callback"], "token_endpoint_auth_method": "none" } ``` The `client_id` must be an **https URL with a path** (a bare origin like `https://app.example.com` is not treated as a document URL and falls through to a registry lookup), and it must equal the URL the document is served from — that equality is what stops any host claiming to be any client. Authorizer fetches it through an SSRF-hardened client (one-shot DNS, dial pinned to the validated IP, private and loopback addresses refused), validates the presented `redirect_uri` against the document's list, and caches it with a clamped TTL. Because such a client asserts its own identity, **a consent screen is shown before any code is issued**. It leads with the redirect host — the only fact about the client the server has verified — and warns when a client's redirect URIs are all loopback, since any local process can bind the same port and present the same document. Clients you registered yourself are unaffected. Restrict which hosts may serve a document with `--client-id-metadata-allowed-domains` if you want a closed deployment; leaving it empty accepts any HTTPS host, which is what a public MCP server wants. #### Self-registering clients: CIMD vs DCR Authorizer implements **both**, off by default, and CIMD is the one to prefer. The [MCP authorization spec (2025-11-25)](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization) demoted it. Authorization servers **SHOULD** support Client ID Metadata Documents and **MAY** support DCR, which the spec keeps only *"for backwards compatibility with earlier versions of the MCP authorization spec"*. The client priority order it defines is: pre-registered → CIMD → DCR → prompt the user. The industry moved the same way: | Product | Approach | | --- | --- | | [Auth0](https://auth0.com/ai/docs/mcp/guides/registering-your-mcp-client-application/dynamic-client-registration) | DCR is Enterprise-only, disabled by default, and needs tenant ACLs or a reverse proxy in front. Auth0 recommends CIMD instead for production | | Keycloak | Has had OIDC DCR for years; ships experimental CIMD | | Google Drive's MCP server | Rejects DCR outright (HTTP 400) | | [Anthropic](https://claude.com/docs/connectors/building/authentication) | Steers directory traffic to CIMD or Anthropic-held credentials, because DCR registers a fresh client on every connection | Auth0's stated objections — resource depletion from mass registration, security probing, unvetted misconfigured clients, audit gaps — apply with more force to a self-hosted product, where every operator would inherit an open, unauthenticated write endpoint and unbounded client-row growth. **CIMD is therefore the preferred path.** It makes the `client_id` an HTTPS URL that the authorization server fetches and validates — no write endpoint, no row growth, no schema change. **RFC 7591 DCR ships anyway, behind `--enable-dynamic-client-registration`, for clients that predate CIMD.** Older Claude Code releases (2.1.226) read `client_id_metadata_document_supported: true` and still refused without a `registration_endpoint`; current ones (2.1.333) use CIMD. Without DCR such older clients cannot connect at all. Enabling it does not downgrade anyone: the spec's priority order is pre-registered → CIMD → DCR, so a CIMD-capable client never reaches the DCR path. Auth0's objections are answered rather than ignored: | Risk | Mitigation | | --- | --- | | Mass registration / resource depletion | Per-IP rate limiting plus a hard ceiling on registry rows | | Unvetted, misconfigured clients | PUBLIC clients only — `token_endpoint_auth_method` must be `none`, `client_credentials` is refused, `redirect_uris` must be https or loopback http | | Impersonation of a known product | Consent screen on every authorization, naming the client and leading with the verified redirect host ([RFC 7591 §5](https://www.rfc-editor.org/rfc/rfc7591.html#section-5) asks for this warning) | | Weak client authentication | S256 PKCE required at `/authorize`; implicit response types refused | | Standing client management surface | RFC 7592 not implemented — a self-registered client cannot be read back, modified or deleted through this endpoint | Both mechanisms make client identity **self-asserted**, which is why both go through the same consent screen: the spec requires the authorization server to display the redirect URI hostname and to warn on `localhost`-only clients. ```sh # Preferred: clients that support Client ID Metadata Documents authorizer --mcp-enabled --url=https://auth.example.com \ --enable-client-id-metadata-document # Add DCR only if your client cannot do CIMD (e.g. current Claude Code) authorizer --mcp-enabled --url=https://auth.example.com \ --enable-client-id-metadata-document \ --enable-dynamic-client-registration ``` Registration itself is one unauthenticated POST: ```sh curl -X POST https://auth.example.com/oauth/register \ -H 'Content-Type: application/json' \ -d '{ "client_name": "My MCP Client", "redirect_uris": ["http://127.0.0.1:5599/callback"], "grant_types": ["authorization_code", "refresh_token"], "token_endpoint_auth_method": "none" }' # 201 Created -> {"client_id": "...", "client_id_issued_at": ..., ...} # No client_secret is ever issued: these are public clients. ``` #### Agent delegation (RFC 8693) `/mcp` accepts **delegated** access tokens — the "agent X acting for user Y" kind minted by [token exchange](../enterprise/token-exchange) — as well as ordinary first-party ones. This is what lets an agent ask Authorizer about *its own* authority through the tools it was granted, rather than needing a credential that speaks for the whole user. Mint one by naming the MCP server as the `resource`: ```sh curl -s -X POST https://auth.example.com/oauth/token \ -d grant_type=urn:ietf:params:oauth:grant-type:token-exchange \ -d client_id=$AGENT_ID -d client_secret=$AGENT_SECRET \ -d subject_token=$USER_ACCESS_TOKEN \ -d subject_token_type=urn:ietf:params:oauth:token-type:access_token \ -d actor_token=$AGENT_ACCESS_TOKEN \ -d actor_token_type=urn:ietf:params:oauth:token-type:access_token \ -d resource=https://auth.example.com/mcp ``` `resource=/mcp`, not ``. The two are different audiences and therefore different surfaces: a delegated token bound to the bare URL authenticates GraphQL, REST and gRPC and is **refused** at `/mcp`; this one is the exact mirror. A 401 from `/mcp` is far more often this than a permissions problem — check the `aud` claim first. **The answers are the agent's, not the user's.** `check_permissions` and `list_permissions` evaluate `perms(agent) ∩ perms(user)`, so an agent that was never granted a document is denied it even when the delegating user can read it, and enumeration omits it rather than leaking the name. Supplying an explicit `user` cannot shed the agent half, and a delegated caller naming any *other* subject is refused outright. Two limits worth planning around: - **A delegated token lives 5 minutes and has no refresh token.** The `401` an expired one gets carries the same discovery challenge as any other, but an MCP client cannot refresh its way out — the agent has to redo the exchange. Non-interactive agents that re-exchange on demand fit this well; a long-lived chat session does not. - **Revocation still flows through the user's session.** Logout, password reset and admin revoke all take the agent's access down with them, because the token names the originating session and that session is checked on every call. Verified against a real Claude Code client (2.1.233): a delegated token bound to `/mcp` reports `✔ Connected` and its `check_permissions` calls come back with the agent's intersected answer — `allowed: false` for a document the delegating user *can* read but the agent was never granted. The same token bound to the bare `` fails the connection with `invalid_token`, which is the audience boundary doing its job. The [`with-agent-permissions`](https://github.com/authorizerdev/examples/tree/main/with-agent-permissions) example runs this end to end and asserts the intersection through the real tool surface. ### Exposed tools | Tool | Auth required | Description | | ------------------- | ------------- | ------------------------------------------------------------------- | | `meta` | no | Server feature flags & provider availability. | | `profile` | yes | The authenticated caller's profile. | | `check_permissions` | yes | Batch-evaluate `(relation, object)` permission checks. | | `list_permissions` | yes | List the objects/relations the caller can access. | Each tool's input schema is generated from the underlying proto message, so the arguments match the [REST](./rest-api) and [GraphQL](./graphql-api) request shapes exactly. For example, `check_permissions` accepts: ```json { "checks": [ { "relation": "can_view", "object": "document:1" } ], "user": "optional-explicit-subject" } ``` The schema also lists `contextual_tuples` (per check) and `context`. They are rarely useful through MCP: a delegated (agent) token may not send either, and `context` is accepted only from a super-admin. Conditions stored on tuples, such as [time-limited grants](./fga-guide#conditions-cel--with), are still evaluated, using the server's clock. ### Errors When a tool call fails — bad arguments, an unauthenticated call, or a permission denial — the server returns an MCP tool result with `isError: true` and the error message as text, so the host surfaces it to the model as a recoverable failure (not a protocol abort). Typical messages mirror the gRPC status: `Unauthenticated`, `PermissionDenied`, `FailedPrecondition` (e.g. *fine-grained authorization is not enabled*). ### Authorizer as the authorization server protecting *your own* MCP server Everything above is about Authorizer's **own** MCP surface. The other direction is just as common: your MCP server, hosted anywhere, needs a real OAuth 2.1 authorization server in front of it, and Authorizer can be that AS. Same specs, different division of labour — there, you implement the resource-server half: | Spec | What it says | Who implements it | | --- | --- | --- | | OAuth 2.1 | Bearer tokens, token endpoint, client auth | **Authorizer** (`/oauth/token`, JWKS, OIDC discovery) | | [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) (protected resource metadata) | Your resource server publishes `/.well-known/oauth-protected-resource` naming its `resource` URI and `authorization_servers`, pointed at from a `401` `WWW-Authenticate` header | **your MCP server** | | [RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707) (resource indicators) | The client passes `resource=` when requesting a token; the AS binds the token's `aud` to it | **Authorizer** binds it (see the `resource` parameter on the [Authorization Endpoint](./oauth2-oidc#authorization-endpoint) and [Token Exchange](../enterprise/token-exchange)); **your MCP server** enforces `aud` on every call | | [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) (token exchange) | An agent gets a token that says "agent X acting for user Y" — see [Token Exchange & Delegation](../enterprise/token-exchange) | **Authorizer** (`grant_type=...token-exchange` on `/oauth/token`) | Authorizer also serves the [RFC 8414 alias](./oauth2-oidc#rfc-8414-alias) `/.well-known/oauth-authorization-server` — the identical metadata document as `/.well-known/openid-configuration` — for MCP clients that probe the OAuth-only discovery path instead of falling back to OIDC discovery. The [`with-mcp`](https://github.com/authorizerdev/examples/tree/main/with-mcp) example builds this end to end: a ~150-line Express MCP server that validates Authorizer-issued JWTs (issuer + `aud`) and a client walkthrough that goes 401 → RFC 9728 discovery → `client_credentials` without `resource` (rejected — wrong `aud`) and with it (accepted) → [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) token exchange with `resource=` → 200. Its first half covers this page's built-in MCP server, for the "which one do I want" question. ### See also - [Authorization (FGA)](./authorization) — the relationship model behind the permission tools. - [REST API](./rest-api) / [GraphQL API](./graphql-api) — the same operations over HTTP. - [FGA Guide](./fga-guide) — building an authorization model and writing tuples. - [OAuth2 / OIDC](./oauth2-oidc) — the authorization-server surface used to protect a custom MCP server. - [Token Exchange & Delegation](../enterprise/token-exchange) — agent-acting-for-user delegated tokens (RFC 8693). --- ## Metrics & Monitoring Authorizer exposes Prometheus-compatible metrics for monitoring authentication activity, API performance, security events, and infrastructure health. ### Endpoints #### `/healthz` - Liveness Probe Returns storage health status. Use with Kubernetes liveness probes. ```bash curl http://localhost:8080/healthz # {"status":"ok"} ``` Returns `503` with `{"status":"unhealthy","error":"storage unavailable"}` when the database is unreachable (details are logged server-side only). #### `/readyz` - Readiness Probe Checks storage and memory store health. Use with Kubernetes readiness probes. ```bash curl http://localhost:8080/readyz # {"status":"ready"} ``` Returns `503` with `{"status":"not ready","error":"storage unavailable"}` when the system is not ready to serve traffic (details are logged server-side only). #### `/metrics` - Prometheus Metrics Serves all metrics in [Prometheus](https://prometheus.io) exposition format. **`/metrics` is never on the main HTTP server.** It is always served by a **separate minimal HTTP server** that runs in parallel with the main Gin app (same pattern as running distinct app and metrics listeners). By default `--http-port` is `8080` and `--metrics-port` is `8081`; **`--http-port` and `--metrics-port` must differ** or the process exits at startup. The metrics listener is **not** reachable from other machines by default: **`--metrics-host` defaults to `127.0.0.1`**, so only loopback can scrape unless you change it (see below). ```bash curl http://127.0.0.1:8081/metrics ``` ##### Bind address and security - **Single host / node-exporter style:** Keep defaults (`127.0.0.1` + `--metrics-port`). Run Prometheus (or an agent) **on the same host** and scrape `127.0.0.1:8081`, or use a reverse proxy that forwards from an internal network to that socket. - **Docker / Kubernetes / another machine scrapes the pod:** Set **`--metrics-host=0.0.0.0`** (or the pod IP interface you use) so the metrics port accepts connections on the container network. **Do not** put the metrics port on a public ingress or internet-facing load balancer; use a **ClusterIP** Service (or internal Docker network) and scrape from inside the cluster only. For **Docker `EXPOSE` vs `-p` / Compose `ports:`** and Kubernetes **pod vs Service** exposure, see [Docker deployment](../deployment/docker#docker-ports-exposure) and [Kubernetes deployment](../deployment/kubernetes#k8s-ports-services). ### Available Metrics #### HTTP Metrics | Metric | Type | Labels | Description | |--------|------|--------|-------------| | `authorizer_http_requests_total` | Counter | `method`, `path`, `status` | Total HTTP requests received | | `authorizer_http_request_duration_seconds` | Histogram | `method`, `path` | HTTP request latency in seconds | For routes that do not match a registered Gin pattern, `path` is recorded as `unmatched` (not the raw URL), to keep Prometheus cardinality bounded. #### Authentication Metrics | Metric | Type | Labels | Description | |--------|------|--------|-------------| | `authorizer_auth_events_total` | Counter | `event`, `status` | Authentication event count | | `authorizer_active_sessions` | Gauge | — | Approximate active session count | | `authorizer_api_operations_total` | Counter | `protocol`, `operation`, `status` | API operations served, attributed to the protocol they came in on | The `protocol` label on `authorizer_api_operations_total` is one of `graphql`, `grpc`, or `rest` (the `rest` value covers calls made through the grpc-gateway `/v1/*` surface). `operation` is the gRPC method / GraphQL operation name and `status` is `ok` or `error`. The same protocol is also recorded on each audit-log entry (under the `protocol` key of the entry's `metadata` field), so operations are attributable to their transport in both metrics and the audit trail. **Auth event values:** | Event | Description | |-------|-------------| | `login` | User email/password login | | `signup` | New user registration | | `logout` | User session termination | | `forgot_password` | Password reset request | | `reset_password` | Password reset completion | | `verify_email` | Email verification | | `verify_otp` | OTP verification | | `magic_link_login` | Magic link authentication | | `admin_login` | Admin dashboard login | | `admin_logout` | Admin dashboard logout | | `oauth_login` | OAuth provider redirect | | `oauth_callback` | OAuth provider callback | | `token_refresh` | Token refresh | | `token_revoke` | Token revocation | **Status values:** `success`, `failure` #### Security Metrics | Metric | Type | Labels | Description | |--------|------|--------|-------------| | `authorizer_security_events_total` | Counter | `event`, `reason` | Security-sensitive events for alerting | | `authorizer_client_id_header_missing_total` | Counter | — | Requests with no `X-Authorizer-Client-ID` header (allowed for some routes) | **Security event examples:** | Event | Reason | Trigger | |-------|--------|---------| | `invalid_credentials` | `bad_password` | Failed password comparison | | `invalid_credentials` | `user_not_found` | Login with non-existent email | | `account_revoked` | `login_attempt` | Login to a revoked account | | `invalid_admin_secret` | `admin_login` | Failed admin authentication | #### GraphQL Metrics | Metric | Type | Labels | Description | |--------|------|--------|-------------| | `authorizer_graphql_errors_total` | Counter | `operation` | GraphQL responses containing errors (HTTP 200 with errors) | | `authorizer_graphql_request_duration_seconds` | Histogram | `operation` | GraphQL operation latency | | `authorizer_graphql_limit_rejections_total` | Counter | `limit` | Operations rejected for exceeding a configured query limit | The `operation` label is **`anonymous`** for unnamed operations, or **`op_` + a short SHA-256 prefix** of the operation name so client-controlled names cannot create unbounded time series. GraphQL APIs return HTTP 200 even when the response contains errors. These metrics capture those application-level errors that would otherwise be invisible to HTTP-level monitoring. The `limit` label on `authorizer_graphql_limit_rejections_total` is one of: | Value | What was exceeded | Tunable via | |---|---|---| | `depth` | Selection-set nesting depth | `--graphql-max-depth` | | `complexity` | Total complexity score | `--graphql-max-complexity` | | `alias` | Total aliased fields per operation | `--graphql-max-aliases` | | `body_size` | HTTP request body size | `--graphql-max-body-bytes` | A sustained non-zero rate on any label usually means either an exploration attempt or a legitimate operation that needs the limit raised. Alert at the rate that distinguishes the two for your traffic profile. See [GraphQL hardening](./security#graphql-hardening) for the limits themselves. #### Authorization (FGA) Metrics These metrics cover the embedded fine-grained authorization ([OpenFGA](https://openfga.dev)) engine. They appear only once FGA is enabled and the corresponding operation has run at least once. See [Authorization (FGA)](./authorization). | Metric | Type | Labels | Description | |--------|------|--------|-------------| | `authorizer_fga_checks_total` | Counter | `operation`, `result` | Access decisions from `check_permissions`. The headline metric for adoption and denial/error alerting. | | `authorizer_fga_check_duration_seconds` | Histogram | `operation` | Latency of the client-facing FGA engine reads. | | `authorizer_fga_operations_total` | Counter | `operation`, `result` | Non-decision FGA operations (model/tuple management, enumeration, reset) by outcome. | | `authorizer_fga_delegated_checks_total` | Counter | `operation`, `outcome` | Decisions for **delegated** (agent-acting-for-user) callers, and which side of the intersection refused. Ordinary callers never appear here. | **`authorizer_fga_checks_total` labels:** | Label | Values | |---|---| | `operation` | `check_permissions` (each supplied pair is counted individually) | | `result` | `allowed` · `denied` · `error` (the engine call failed — fail-closed, so the caller was denied) | **`authorizer_fga_delegated_checks_total` labels:** | Label | Values | |---|---| | `operation` | `check_permissions` · `list_permissions` (see note below) | | `outcome` | `allowed` · `denied_by_agent` · `denied_by_user` · `not_enforced` | The `outcome` label is what makes an intersection denial diagnosable: - **`denied_by_agent`** — the agent has no grant of its own. The user may well have access. Fix: grant the **agent** a tuple. - **`denied_by_user`** — the agent had its grant, the delegating user does not. This is the Confused Deputy being stopped. Do **not** widen the agent; it cannot help, and the user genuinely lacks access. - **`not_enforced`** — a delegated caller arrived but the active model declares no `agent` type, so the agent half of the intersection could not be evaluated. By default the check is **denied**; with `--fga-allow-unconstrained-agents` set it is authorized as the **delegating user alone**, with the agent unconstrained. Only `check_permissions` emits `allowed` / `denied_by_agent` / `denied_by_user`. `list_permissions` intersects object *sets* rather than folding a per-check decision, so it can only ever report `not_enforced`. `not_enforced` is the one to alert on. It is the only outcome that reports a security property *not* being enforced, and it is silent by construction: the request succeeds and nothing in the response says the agent was unconstrained. See [Agent Identity & Permissions](../enterprise/agent-identity#observability). **`authorizer_fga_check_duration_seconds`** `operation`: `check_permissions` · `list_permissions`. The histogram's `_count` also gives you a call rate per operation for free. **`authorizer_fga_operations_total`** `operation`: `get_model` · `write_model` · `read_tuples` · `write_tuples` · `delete_tuples` · `list_users` · `expand` · `list_permissions` · `reset`. `result`: `success` · `error`. Useful queries: ```promql # FGA denial rate (last 5 minutes) sum(rate(authorizer_fga_checks_total{result="denied"}[5m])) # FGA check error rate — should be ~0; a spike means the engine/store is failing closed sum(rate(authorizer_fga_checks_total{result="error"}[5m])) # Admin authorization changes (model/tuple writes, resets) sum by (operation) (increase(authorizer_fga_operations_total{operation=~"write_model|write_tuples|delete_tuples|reset"}[1h])) # p99 check latency histogram_quantile(0.99, sum by (le, operation) (rate(authorizer_fga_check_duration_seconds_bucket[5m]))) ``` A non-zero `result="error"` rate on `authorizer_fga_checks_total` is an operational signal — the engine or its datastore is failing, and checks are denying as a result. Page on it. #### Infrastructure Metrics | Metric | Type | Labels | Description | |--------|------|--------|-------------| | `authorizer_db_health_check_total` | Counter | `status` | Database health check outcomes (`healthy`/`unhealthy`) | ### Prometheus Configuration Add Authorizer as a scrape target in your `prometheus.yml`: ```yaml scrape_configs: - job_name: 'authorizer' scrape_interval: 15s static_configs: # In Docker/K8s, use --metrics-host=0.0.0.0 so the scraper can reach the pod/container; scrape via internal DNS/service. - targets: ['authorizer:8081'] # default --metrics-port; same host only: use 127.0.0.1:8081 ``` For Kubernetes with service discovery: ```yaml scrape_configs: - job_name: 'authorizer' kubernetes_sd_configs: - role: pod relabel_configs: - source_labels: [__meta_kubernetes_pod_label_app] regex: authorizer action: keep - source_labels: [__meta_kubernetes_pod_ip] target_label: __address__ replacement: '$1:8081' # metrics port; ensure deployment sets --metrics-host=0.0.0.0 for in-cluster scrape ``` ### Grafana Dashboard #### Suggested Panels **Authentication Overview:** ```promql # Login success rate (last 5 minutes) rate(authorizer_auth_events_total{event="login",status="success"}[5m]) / rate(authorizer_auth_events_total{event="login"}[5m]) # Signup rate rate(authorizer_auth_events_total{event="signup",status="success"}[5m]) # Active sessions authorizer_active_sessions ``` **Security Alerts:** ```promql # Failed login rate (alert if > 10/min) rate(authorizer_security_events_total{event="invalid_credentials"}[1m]) > 10 # Failed admin login attempts increase(authorizer_security_events_total{event="invalid_admin_secret"}[5m]) # Revoked account login attempts increase(authorizer_security_events_total{event="account_revoked"}[5m]) ``` **API Performance:** ```promql # GraphQL p99 latency histogram_quantile(0.99, rate(authorizer_graphql_request_duration_seconds_bucket[5m])) # HTTP p95 latency by path histogram_quantile(0.95, sum(rate(authorizer_http_request_duration_seconds_bucket[5m])) by (le, path)) # GraphQL error rate rate(authorizer_graphql_errors_total[5m]) ``` **Infrastructure:** ```promql # Database health check failure rate rate(authorizer_db_health_check_total{status="unhealthy"}[5m]) # Request rate by endpoint sum(rate(authorizer_http_requests_total[5m])) by (path) ``` ### Alerting Rules Example Prometheus alerting rules: ```yaml groups: - name: authorizer rules: - alert: HighLoginFailureRate expr: rate(authorizer_security_events_total{event="invalid_credentials"}[5m]) > 0.5 for: 2m labels: severity: warning annotations: summary: "High login failure rate detected" description: "More than 0.5 failed logins/sec for 2 minutes — possible brute force." - alert: DatabaseUnhealthy expr: authorizer_db_health_check_total{status="unhealthy"} > 0 for: 1m labels: severity: critical annotations: summary: "Authorizer database health check failing" - alert: HighGraphQLErrorRate expr: rate(authorizer_graphql_errors_total[5m]) > 1 for: 5m labels: severity: warning annotations: summary: "Elevated GraphQL error rate" ``` ### Manual Testing Start Authorizer and verify metrics are working: ```bash # 1. Start Authorizer (dev mode with SQLite) make dev # 2. Check health endpoints curl http://localhost:8080/healthz curl http://localhost:8080/readyz # 3. View raw metrics (default: loopback + metrics port) curl http://127.0.0.1:8081/metrics # 4. Generate some auth events via GraphQL curl -X POST http://localhost:8080/graphql \ -H "Content-Type: application/json" \ -d '{"query":"mutation { login(params: {email: \"test@example.com\", password: \"wrong\"}) { message } }"}' # 5. Check metrics again — look for auth and security counters curl -s http://127.0.0.1:8081/metrics | grep authorizer_auth curl -s http://127.0.0.1:8081/metrics | grep authorizer_security curl -s http://127.0.0.1:8081/metrics | grep authorizer_graphql # 6. Run integration tests TEST_DBS="sqlite" go test -p 1 -v -run "TestMetrics|TestHealth|TestReady|TestAuthEvent|TestAdminLoginMetrics|TestGraphQLError" ./internal/integration_tests/ ``` ### CLI Flags | Flag | Default | Description | |------|---------|-------------| | `--metrics-port` | `8081` | Port for the dedicated Prometheus `/metrics` listener (**must differ** from `--http-port`) | | `--metrics-host` | `127.0.0.1` | Bind address for that dedicated listener only (use `0.0.0.0` for in-cluster or cross-container scrape; never expose on the public internet without a proxy and auth) | `/healthz`, `/readyz`, and `/health` stay on the **main HTTP** port (`--host`:`--http-port`). `/metrics` is **only** on the dedicated listener (`--metrics-host`:`--metrics-port`). --- ## OAuth 2.0, OIDC & SSO ## OAuth 2.0, OpenID Connect & SSO Authorizer is a fully conformant OAuth 2.0 and [OpenID Connect](https://openid.net/specs/openid-connect-core-1_0.html) (OIDC) provider. You can: - **Use it standalone** as an SSO identity provider for your own apps — any OIDC-compliant client library "just works" against its Discovery URL. - **Federate it into an existing SSO** (Auth0, Okta, Keycloak, etc.) as an upstream OIDC identity provider. - **Use it alongside social providers** (Google, GitHub, Facebook, LinkedIn, Apple, Discord, Twitter, Twitch, Roblox, Microsoft). This page is the one-stop reference for every endpoint, parameter, and integration pattern Authorizer supports, plus a practical testing guide at the end. ### Standards Implemented | Standard | Status | Notes | | ------------------------------------- | ------------- | ------------------------------------------------------------------ | | OIDC Core 1.0 | Implemented | ID tokens, UserInfo, nonce, `auth_time`, `amr`, `acr`, `at_hash`, `c_hash`, `azp` | | OIDC Discovery 1.0 | Implemented | All required + recommended fields | | OIDC Hybrid Flow (§3.3) | Implemented | `code id_token`, `code token`, `code id_token token`, `id_token token` | | OIDC RP-Initiated Logout 1.0 | Implemented | `post_logout_redirect_uri`, `state` echo, `id_token_hint` | | OIDC Back-Channel Logout 1.0 | Implemented | Opt-in via `--backchannel-logout-uri` | | [RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749) (OAuth 2.0) | Implemented | Authorization Code + Refresh Token + Implicit + Client Credentials grants | | RFC 6750 (Bearer Token) | Implemented | `WWW-Authenticate` on 401 | | RFC 7009 (Token Revocation) | Implemented | Returns 200 for invalid tokens | | RFC 7517 (JWK) | Implemented | RSA, ECDSA, HMAC; manual multi-key rotation | | [RFC 7523](https://datatracker.ietf.org/doc/html/rfc7523) (JWT client assertions) | Implemented | `private_key_jwt` via [trusted issuers](../enterprise/workload-identity) — K8s SA tokens, [SPIFFE](https://spiffe.io) JWT-SVIDs | | [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636) (PKCE) | Implemented | `S256` and `plain` methods; defaults to `plain` when the method is omitted (§4.2) | | RFC 7662 (Token Introspection) | Implemented | Non-disclosure for inactive tokens | | RFC 8414 (Authorization Server Metadata) | Implemented | `/.well-known/oauth-authorization-server` — alias of the OIDC discovery document | | [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) (Token Exchange) | Implemented | [Delegation-only profile](../enterprise/token-exchange) with nested `act` chain | | [RFC 9068](https://datatracker.ietf.org/doc/html/rfc9068) (JWT Access Tokens) | Partial | `client_id` claim on every access token; delegated tokens also carry `typ: at+jwt`. See [Token claims](#token-claims) | | RFC 8707 (Resource Indicators) | Implemented | Optional `resource` on `/authorize` + `/oauth/token` (authorization code flow); exactly one required on the token-exchange grant | **Not yet implemented** (tracked for future releases): RFC 9101 JAR / Request Object, OIDC Session Management iframe, front-channel logout, automated time-based key rotation. RFC 7591 dynamic client registration IS implemented as of 2.4.0, but it is **off by default** — see [Self-registering clients](./mcp#self-registering-clients-cimd-vs-dcr). --- ### Quickstart: Authorizer as an SSO Provider This is the most common setup — an app delegates authentication to Authorizer via OIDC. #### Step 1 — Configure your Authorizer instance Before any client can use Authorizer for SSO, you need to tell the server which origins and redirect URIs are allowed. ```bash ./authorizer \ --client-id=my-app \ --client-secret="$(openssl rand -hex 32)" \ --allowed-origins=https://app.example.com,http://localhost:3000 \ --jwt-type=RS256 \ --jwt-private-key="$(cat /etc/authorizer/jwt-private.pem)" \ --jwt-public-key="$(cat /etc/authorizer/jwt-public.pem)" \ --encryption-key=your-encryption-key ``` For production, use RSA or ECDSA keys (not HMAC) so public clients can verify tokens via the JWKS endpoint without sharing the signing secret. See the [Server Configuration guide](./server-config) for all flags. #### Step 2 — Give your app the Discovery URL One URL is all a spec-compliant OIDC client library needs: ``` https://your-authorizer.example/.well-known/openid-configuration ``` Every library (Auth0.js, openid-client, go-oidc, python-jose, Spring Security OAuth, etc.) can bootstrap from this single URL. No hand-wiring of endpoint URLs needed. #### Step 3 — Wire your client The following examples all implement the same Authorization Code + PKCE flow. Pick the one matching your stack. ##### React SPA (using `@authorizerdev/authorizer-react`) Authorizer ships an official React SDK that wraps OIDC for you: ```bash npm install @authorizerdev/authorizer-react ``` ```jsx import { AuthorizerProvider, useAuthorizer } from '@authorizerdev/authorizer-react'; function App() { return ( ); } function MyApp() { const { user, loading, authorizerRef } = useAuthorizer(); if (loading) return

Loading…

; if (!user) { return ; } return

Hello {user.email}

; } ``` ##### Generic SPA (using `oidc-client-ts`) For a framework-agnostic JavaScript app using a standards-compliant OIDC library: ```bash npm install oidc-client-ts ``` ```javascript import { UserManager, WebStorageStateStore } from 'oidc-client-ts'; const mgr = new UserManager({ authority: 'https://your-authorizer.example', client_id: 'my-app', redirect_uri: `${window.location.origin}/callback`, post_logout_redirect_uri: window.location.origin, response_type: 'code', scope: 'openid profile email offline_access', userStore: new WebStorageStateStore({ store: window.localStorage }), }); // Trigger sign-in document.querySelector('#login').addEventListener('click', () => mgr.signinRedirect()); // On the /callback page const user = await mgr.signinRedirectCallback(); console.log('signed in as', user.profile.email); ``` ##### Node.js / Express backend (using `openid-client`) ```bash npm install openid-client express-session ``` ```javascript import express from 'express'; import session from 'express-session'; import { Issuer, generators } from 'openid-client'; const app = express(); app.use(session({ secret: 'change-me', resave: false, saveUninitialized: true })); // Discover Authorizer and build a Client const authorizer = await Issuer.discover('https://your-authorizer.example'); const client = new authorizer.Client({ client_id: 'my-app', client_secret: process.env.CLIENT_SECRET, redirect_uris: ['http://localhost:3000/callback'], response_types: ['code'], }); app.get('/login', (req, res) => { const code_verifier = generators.codeVerifier(); const code_challenge = generators.codeChallenge(code_verifier); req.session.code_verifier = code_verifier; res.redirect(client.authorizationUrl({ scope: 'openid profile email offline_access', code_challenge, code_challenge_method: 'S256', })); }); app.get('/callback', async (req, res) => { const params = client.callbackParams(req); const tokenSet = await client.callback( 'http://localhost:3000/callback', params, { code_verifier: req.session.code_verifier }, ); req.session.tokens = tokenSet; const userinfo = await client.userinfo(tokenSet.access_token); res.json({ claims: tokenSet.claims(), userinfo }); }); app.listen(3000); ``` ##### Go backend (using `coreos/go-oidc`) ```bash go get github.com/coreos/go-oidc/v3/oidc golang.org/x/oauth2 ``` ```go package main import ( "context" "encoding/json" "log" "net/http" "github.com/coreos/go-oidc/v3/oidc" "golang.org/x/oauth2" ) func main() { ctx := context.Background() provider, err := oidc.NewProvider(ctx, "https://your-authorizer.example") if err != nil { log.Fatal(err) } verifier := provider.Verifier(&oidc.Config{ClientID: "my-app"}) cfg := oauth2.Config{ ClientID: "my-app", ClientSecret: "your-client-secret", RedirectURL: "http://localhost:8000/callback", Endpoint: provider.Endpoint(), Scopes: []string{oidc.ScopeOpenID, "profile", "email", "offline_access"}, } http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, cfg.AuthCodeURL("state-token"), http.StatusFound) }) http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { token, err := cfg.Exchange(ctx, r.URL.Query().Get("code")) if err != nil { http.Error(w, err.Error(), 500) return } rawIDToken := token.Extra("id_token").(string) idToken, err := verifier.Verify(ctx, rawIDToken) if err != nil { http.Error(w, err.Error(), 500) return } var claims struct { Email string `json:"email"` Sub string `json:"sub"` } idToken.Claims(&claims) json.NewEncoder(w).Encode(claims) }) log.Fatal(http.ListenAndServe(":8000", nil)) } ``` ##### Python / FastAPI backend (using `authlib`) ```bash pip install authlib fastapi uvicorn itsdangerous ``` ```python from fastapi import FastAPI, Request from starlette.middleware.sessions import SessionMiddleware from starlette.responses import RedirectResponse from authlib.integrations.starlette_client import OAuth app = FastAPI() app.add_middleware(SessionMiddleware, secret_key="change-me") oauth = OAuth() oauth.register( name="authorizer", server_metadata_url="https://your-authorizer.example/.well-known/openid-configuration", client_id="my-app", client_secret="your-client-secret", client_kwargs={"scope": "openid profile email offline_access"}, ) @app.get("/login") async def login(request: Request): redirect_uri = request.url_for("callback") return await oauth.authorizer.authorize_redirect(request, redirect_uri) @app.get("/callback", name="callback") async def callback(request: Request): token = await oauth.authorizer.authorize_access_token(request) return {"claims": token.get("userinfo")} ``` ##### Mobile (Flutter) Use the official Flutter SDK: ```dart dependencies: authorizer_flutter: ^latest ``` See the [Flutter SDK docs](../sdks/authorizer-flutter) for the full API. ##### Other frameworks Any framework with an OIDC library will work — ASP.NET Core (`Microsoft.AspNetCore.Authentication.OpenIdConnect`), Spring Boot (`spring-security-oauth2-client`), Rails (`omniauth_openid_connect`), Laravel (`socialite-providers/openid`), and so on. Point them at the Discovery URL and set `client_id` / `client_secret`. --- ### Integrating Authorizer with an Existing SSO If you already run a commercial or enterprise SSO (Auth0, Okta, Keycloak, Azure AD, Ping) and want to add Authorizer as an **upstream identity source**, every major platform supports this via OIDC federation. Authorizer behaves like any other third-party OIDC provider. Typical reasons to do this: - **Bring-your-own-identity for a customer segment** — let customers on a self-hosted plan authenticate via Authorizer while everyone else uses your primary SSO. - **Cost offload** — route high-volume, low-margin users through Authorizer to avoid per-MAU billing on your main SSO. - **Private-label multi-tenancy** — each tenant runs their own Authorizer instance, federated into a central Auth0. - **On-premise / air-gapped** — keep sensitive identities inside a self-hosted Authorizer and federate only short-lived tokens out. #### Auth0: Add Authorizer as an Enterprise OIDC Connection Auth0 calls third-party OIDC identity providers **Enterprise Connections**. 1. **Register Auth0 as an Authorizer client.** In your Authorizer instance, set the `--client-id` and `--client-secret` that Auth0 will use, and include Auth0's callback URL in `--allowed-origins`: ```bash ./authorizer \ --client-id=auth0-upstream \ --client-secret="$(openssl rand -hex 32)" \ --allowed-origins=https://YOUR_TENANT.auth0.com ``` Auth0's OIDC callback URL will be `https://YOUR_TENANT.auth0.com/login/callback` — add that to `--allowed-origins`. 2. **In Auth0 Dashboard → Authentication → Enterprise → OpenID Connect → Create Connection**, fill in: - **Connection Name**: e.g. `authorizer` - **Issuer URL**: `https://your-authorizer.example` — Auth0 fetches `/.well-known/openid-configuration` automatically - **Client ID**: `auth0-upstream` (the value you configured in step 1) - **Client Secret**: the secret from step 1 - **Type**: Back Channel (authorization code flow with client_secret) - **Scopes**: `openid profile email` - Enable **Sync user profile attributes at each login** 3. **Enable the connection for your Auth0 applications.** Under the connection → Applications tab, toggle on each Auth0 app that should see the new IdP. 4. **Test.** Open an Auth0 Universal Login page — you should see a new button labeled `authorizer` (or whatever you named the connection). Clicking it redirects through Authorizer and lands back on your Auth0 app as a normal Auth0 user. **What Auth0 does under the hood:** it calls Authorizer's `/authorize` endpoint with a code-flow request, exchanges the code at `/oauth/token`, verifies the ID token via `/.well-known/jwks.json`, and calls `/userinfo` to populate the Auth0 user profile. All of these endpoints are implemented by Authorizer. Three Auth0 quirks Authorizer handles for you: Auth0 always sends a `nonce` (even for the code flow, where OIDC makes it optional) and validates it against the ID token; it uses `response_mode=form_post` for the authorization response; and it may send a `code_challenge` without `code_challenge_method`, in which case Authorizer defaults to `plain` per RFC 7636 §4.2. #### Okta: Add Authorizer as an Identity Provider Okta's equivalent feature is called **Identity Providers**. 1. Register Okta's callback URL in Authorizer's `--allowed-origins`: `https://YOUR_OKTA_DOMAIN/oauth2/v1/authorize/callback` 2. In Okta Admin Console → **Security → Identity Providers → Add Identity Provider → OpenID Connect IdP**: - **IdP Type**: OIDC - **Client ID** / **Client Secret**: the Authorizer client credentials - **Scopes**: `openid profile email` - **Issuer**: `https://your-authorizer.example` - **Authorization endpoint**: copy from Authorizer's discovery document - **Token endpoint**, **JWKS endpoint**, **UserInfo endpoint**: copy from discovery - **Authentication type**: `Client Secret` 3. Add a **Routing Rule** so the IdP appears on the Okta sign-in page. 4. Test by visiting the Okta sign-in page — the new IdP button appears. #### Keycloak: Add Authorizer as an Identity Provider Keycloak's equivalent is **Identity Providers** as well. 1. Register Keycloak's callback URL: `https://YOUR_KEYCLOAK/realms/YOUR_REALM/broker/authorizer/endpoint` 2. In Keycloak Admin → **Identity Providers → Add provider → OpenID Connect v1.0**: - **Alias**: `authorizer` - **Discovery endpoint**: `https://your-authorizer.example/.well-known/openid-configuration` — click **Import** to autofill the rest - **Client ID** / **Client Secret**: the Authorizer client credentials - **Default Scopes**: `openid profile email` 3. Save. The new IdP will appear on the Keycloak login page. #### Azure AD B2C / Microsoft Entra External ID Microsoft Entra External ID supports custom OIDC identity providers. In **Identity Providers → New OpenID Connect provider**, supply the Authorizer metadata URL, client ID, and client secret. Map the `sub` claim to `issuerUserId` and `email` to `email`. #### Generic pattern Any SSO product that supports OIDC federation uses the same inputs: | Input | Value | |--------------------------|---------------------------------------------------------------| | Issuer / Discovery URL | `https://your-authorizer.example/.well-known/openid-configuration` | | Client ID | Set via `--client-id` on Authorizer | | Client Secret | Set via `--client-secret` on Authorizer | | Scopes | `openid profile email` (+ `offline_access` if you need refresh) | | Redirect / Callback URL | Provided by the downstream SSO — must be added to Authorizer's `--allowed-origins` | | Signing algorithm | Whatever `--jwt-type` is set to (prefer RSA/ECDSA) | --- ### Endpoint Reference #### OpenID Connect Discovery **Endpoint:** `GET /.well-known/openid-configuration` **Spec:** [OpenID Connect Discovery 1.0](https://openid.net/specs/openid-connect-discovery-1_0.html) Returns metadata so clients can auto-configure themselves. **Selected response fields:** | Field | Value / Notes | | ----------------------------------------------------- | ------------------------------------------------------------------------------------ | | `issuer` | Base URL of the Authorizer instance | | `authorization_endpoint` | URL for `/authorize` | | `token_endpoint` | URL for `/oauth/token` | | `userinfo_endpoint` | URL for `/userinfo` | | `jwks_uri` | URL for `/.well-known/jwks.json` | | `introspection_endpoint` | URL for `/oauth/introspect` | | `revocation_endpoint` | URL for `/oauth/revoke` | | `end_session_endpoint` | URL for `/logout` | | `response_types_supported` | `["code", "token", "id_token", "code id_token", "code token", "code id_token token", "id_token token"]` | | `grant_types_supported` | `["authorization_code", "refresh_token", "client_credentials", "implicit", "urn:ietf:params:oauth:grant-type:token-exchange"]`, plus `urn:openid:params:grant-type:ciba` with `--enable-ciba` | | `backchannel_authentication_endpoint` | `/oauth/bc-authorize`, only with `--enable-ciba` ([CIBA](../enterprise/ciba)) | | `backchannel_token_delivery_modes_supported` | `["poll"]`, only with `--enable-ciba` | | `backchannel_user_code_parameter_supported` | `false`, only with `--enable-ciba` | | `authorization_details_types_supported` | The `--ciba-authorization-details-types` list, only with `--enable-ciba` and when the list is set | | `scopes_supported` | `["openid", "email", "profile", "phone", "offline_access"]` | | `response_modes_supported` | `["query", "fragment", "form_post", "web_message"]` | | `code_challenge_methods_supported` | `["S256", "plain"]` — `["S256"]` only when `--oauth2-1-strict` is set | | `resource_indicators_supported` | `true` (RFC 8707) | | `id_token_signing_alg_values_supported` | Includes configured `--jwt-type` and always `RS256` | | `token_endpoint_auth_methods_supported` | `["client_secret_basic", "client_secret_post", "none", "private_key_jwt"]` (`none` = public client with PKCE) | | `introspection_endpoint_auth_methods_supported` | `["client_secret_basic", "client_secret_post"]` | | `revocation_endpoint_auth_methods_supported` | `["client_secret_basic", "client_secret_post"]` | | `claims_supported` | Includes `sub`, `iss`, `aud`, `azp`, `exp`, `iat`, `auth_time`, `amr`, `acr`, `at_hash`, `c_hash`, `nonce`, `email`, `email_verified`, `given_name`, `family_name`, profile claims | | `backchannel_logout_supported` | `true` iff `--backchannel-logout-uri` is configured | | `backchannel_logout_session_supported` | Same as above | ```bash curl https://your-authorizer.example/.well-known/openid-configuration ``` ##### RFC 8414 alias **Endpoint:** `GET /.well-known/oauth-authorization-server` A thin alias serving the identical document as `/.well-known/openid-configuration` — added for clients that only know [RFC 8414](https://www.rfc-editor.org/rfc/rfc8414) (OAuth 2.0 Authorization Server Metadata) and probe this path first without falling back to OIDC discovery. This matters for OAuth-only clients like remote MCP hosts implementing the [MCP Authorization spec](https://modelcontextprotocol.io), which is layered on RFC 8414/8707 rather than full OIDC. The response also advertises `resource_indicators_supported: true` (RFC 8707). #### Authorization Endpoint **Endpoint:** `GET /authorize` **Specs:** [RFC 6749](https://www.rfc-editor.org/rfc/rfc6749) | [RFC 7636 (PKCE)](https://www.rfc-editor.org/rfc/rfc7636) | [OIDC Core 1.0 §3](https://openid.net/specs/openid-connect-core-1_0.html#Authentication) Supported flows: Authorization Code (with PKCE), Implicit, Hybrid. With `--oauth2-1-strict` (default `false`, opt-in and breaking), Authorizer additionally enforces OAuth 2.1: any `response_type` that delivers a bearer token in the fragment (`token`, `id_token token`, `code token`, `code id_token token`) is rejected, and PKCE `plain` is no longer accepted — only `S256`. Discovery's `code_challenge_methods_supported` reflects this (drops `plain` when strict mode is on). Off by default, so existing implicit/ hybrid-with-token and PKCE-plain clients are unaffected until you opt in. **Request parameters:** | Parameter | Required | Notes | | ------------------------ | --------------------------- | ------------------------------------------------------------------------------------- | | `client_id` | Yes | Your application's client ID | | `response_type` | Yes | Any supported single or hybrid combination (see discovery) | | `state` | Yes | Anti-CSRF token (opaque string). Mandatory in Authorizer | | `redirect_uri` | No | Must match a registered redirect URI exactly (RFC 6749 §3.1.2.3) if the client has any registered; otherwise checked against `--allowed-origins` only. Defaults to `/app` | | `scope` | No | Space-separated. Default: `openid profile email` | | `response_mode` | No | `query`, `fragment`, `form_post`, `web_message`. Hybrid flows forbid `query` | | `code_challenge` | Yes, when `code` is in type | PKCE challenge: `BASE64URL(SHA256(code_verifier))` | | `code_challenge_method` | No | `S256` or `plain`; defaults to `plain` when omitted, per RFC 7636 §4.2 | | `nonce` | Recommended | Binds ID token to session; required per OIDC when `response_type` includes `id_token` | | `prompt` | No | `none`, `login`, `consent`, `select_account` (last two are parsed but no-op) | | `max_age` | No | Seconds; `0` forces re-auth; positive values force re-auth if session is older | | `login_hint` | No | Pre-fills the email field on the login UI | | `ui_locales` | No | Forwarded to the login UI as a query parameter | | `id_token_hint` | No | Advisory ID token; invalid hints are ignored (never cause the request to fail) | | `screen_hint` | No | Authorizer extension: `signup` redirects to the signup page | | `resource` | No | RFC 8707 resource indicator (authorization code flow only). Must be an absolute URI with no fragment (`invalid_target` otherwise); repeated values are rejected (`invalid_request`). Bound to the code and must be echoed unchanged at `/oauth/token`; sets the access token's `aud` | **Example authorization code request:** ``` GET /authorize? client_id=YOUR_CLIENT_ID &response_type=code &state=RANDOM_STATE &code_challenge=BASE64URL_SHA256_OF_VERIFIER &code_challenge_method=S256 &redirect_uri=https://yourapp.com/callback &scope=openid%20profile%20email%20offline_access ``` **Example hybrid request (OIDC Core §3.3):** ``` GET /authorize? client_id=YOUR_CLIENT_ID &response_type=code%20id_token &state=RANDOM_STATE &nonce=RANDOM_NONCE &code_challenge=BASE64URL_SHA256_OF_VERIFIER &code_challenge_method=S256 &redirect_uri=https://yourapp.com/callback &scope=openid%20profile%20email &response_mode=fragment ``` The response fragment contains **both** `code=` and `id_token=` in a single round trip. ##### Nonce handling The `nonce` prevents ID token replay: the client sends a random value on `/authorize` and must get the same value back as the `nonce` claim in the ID token. - **Code flow:** OIDC Core makes `nonce` optional here, but enterprise RPs (Auth0, Okta, Keycloak) always send and validate it. Authorizer stores the nonce with the authorization code — including across the login UI round-trip — and embeds it in the ID token issued at `/oauth/token`. - **Implicit flow** (`response_type=id_token` or `id_token token`): `nonce` is **required** per OIDC Core §3.2.2.1; requests without it are rejected with `invalid_request`. ##### Response modes | Mode | Delivery | Notes | |---------------|------------------------------------------------|-----------------------------------------------------| | `query` | Redirect with params in the query string | Only for the `code` flow — tokens never go in URLs; forbidden for hybrid flows | | `fragment` | Redirect with params in the URL fragment | Default for implicit / hybrid flows | | `form_post` | Auto-submitting HTML form `POST` to the RP | Used by Auth0 for Enterprise OIDC connections | | `web_message` | `window.postMessage()` to the RP | For SPA integrations | Error responses (e.g. `login_required` from `prompt=none`) are delivered via the same configured `response_mode`. For `form_post`, Authorizer serves the auto-submitting form with a dedicated `Content-Security-Policy` (nonce-based `script-src`, relaxed `form-action`) so the browser allows the form to POST to the RP's `redirect_uri`. If a reverse proxy in front of Authorizer injects its own CSP header, it can break `form_post` — see [Common Issues](#common-issues). ##### Social login inside an authorization request _Authorizer 2.4.6 and later._ When `/authorize` needs the user to sign in, it sends the browser to the login page at `/app`. If the user picks a social provider (Google, GitHub, …), that login **resumes the original authorization request** instead of finishing on its own: ``` client ──► /authorize ──► /app ──► /oauth_login/github ──► GitHub │ client ◄── /authorize ◄── /app ◄── /oauth_callback/github ◄───┘ (code) (checks redirect_uri, (session cookie only — consent, PKCE) no code, nothing appended) ``` 1. The login page calls `/oauth_login/` with `redirect_uri` set to **its own `/app` URL**, carrying the original `/authorize` parameters in the query string. 2. The provider returns to `/oauth_callback/`, which signs the user in (sets the session cookie) and redirects to that `/app` URL **unchanged**. It does not issue an authorization code and does not append `state`, `nonce` or `code`. 3. `/app` sees the session and replays the request to `/authorize`. `/authorize` then checks `redirect_uri` against the **client's registered redirect URIs**, shows the consent screen if the client requires it, binds PKCE, and redirects to the client with the code. This is the same path password, passkey and OTP login already take, and it is how Auth0 and other providers treat social connections: the provider always returns to the authorization server, and only `/authorize` redirects to the application. It means: - **A client's callback does not have to be in `--allowed-origins`.** A client registered with `https://app.example.org/callback` completes social login with `--allowed-origins` listing only your own console. Do not add client origins to `--allowed-origins` to make social login work: that list also drives CORS, the CSRF origin check and the email-link redirects, for every client. - **Self-registered and CIMD clients always get the consent screen**, including through social login. - **The client's `nonce` reaches the ID token**, because the callback appends nothing for `/app` to forward. **What `/oauth_login` accepts as `redirect_uri`:** this server's own `/app`, `/app/` or `/app/signup` (same scheme and host:port as `--url`, exact path, no fragment), or any URI allowed by `--allowed-origins`. Nothing else, and in particular not a client's registered callback. | `redirect_uri` sent to `/oauth_login` (server `--url=https://auth.example.com`, `--allowed-origins=https://console.example.com`) | Result | |---|---| | `https://auth.example.com/app/?client_id=…&response_type=code&…` | Accepted: resumes through `/authorize`. This is the URL the login page is on: `/app` 301-redirects to `/app/` | | `https://auth.example.com/app?client_id=…&response_type=code&…` | Accepted: same | | `https://auth.example.com/app/signup?client_id=…&…` | Accepted: same, from the signup screen | | `https://console.example.com/dashboard` | Accepted: allowed origin, direct redirect | | `https://app.example.org/callback` (a client's registered callback) | `400 invalid redirect uri`. Go through `/authorize` instead | | `https://auth.example.com/app#client_id=…` | `400`: fragment | | `https://auth.example.com/graphql`, `/app/settings` | `400`: only `/app`, `/app/` and `/app/signup` | | `http://auth.example.com/app?…` | `400`: scheme differs from `--url` | ###### Example: the full round trip A client `c1` is registered with the callback `https://app.example.org/callback`, and the server runs with `--url=https://auth.example.com --allowed-origins=https://console.example.com`. The client's callback is not in `--allowed-origins`, and doesn't need to be. These are the requests the browser makes (line breaks added; values URL-encoded in practice): ```http # 1. The client starts an authorization request. No session yet, so the user is sent to the login page. GET https://auth.example.com/authorize?client_id=c1&response_type=code&response_mode=query &redirect_uri=https://app.example.org/callback&scope=openid profile email &state=st-123&nonce=n-456&code_challenge=E9Mel…&code_challenge_method=S256 → 302 Location: /app?state=st-123&scope=openid profile email&redirect_uri=https://app.example.org/callback &response_mode=query&response_type=code&client_id=c1&nonce=n-456&code_challenge=E9Mel…&code_challenge_method=S256&… GET https://auth.example.com/app?state=st-123&… → 301 Location: /app/?state=st-123&… # the login page renders at /app/ # 2. The user clicks "Continue with GitHub". redirect_uri is the login page's own URL, not the client's callback. GET https://auth.example.com/oauth_login/github?state=st-123&scope=openid profile email &redirect_uri=https://auth.example.com/app/?state=st-123&…&client_id=c1&nonce=n-456&… → 307 Location: https://github.com/login/oauth/authorize?client_id=…&state= # 3. GitHub returns. The callback signs the user in and goes back to the login page URL, byte for byte. GET https://auth.example.com/oauth_callback/github?code=&state= → 302 Location: https://auth.example.com/app/?state=st-123&…&client_id=c1&nonce=n-456&… Set-Cookie: cookie_session=… # 4. /app has a session now, so it replays the original request to /authorize. GET https://auth.example.com/authorize?client_id=c1&response_type=code&…&state=st-123&nonce=n-456&… → 302 Location: https://app.example.org/callback?code=&state=st-123 (or the consent screen first, for a self-registered or CIMD client) # 5. The client redeems the code as usual. POST https://auth.example.com/oauth/token grant_type=authorization_code&code=&client_id=c1 &redirect_uri=https://app.example.org/callback&code_verifier= → 200 {"access_token": "…", "id_token": "…", …} # id_token "nonce" is n-456 ``` Note that steps 3 and 4 never put a code in a URL that `/authorize` didn't produce, and the client only ever sees step 4's redirect. ###### Example: a customised login page The hosted login page does all of this already. If you ship your own build of the login page (served by Authorizer at `/app`), its social buttons need two things. Here they are in plain JavaScript: ```js // The /authorize parameters this page was opened with. /authorize puts them in // the fragment when response_mode=fragment, so read both; the query wins. function authorizeParams() { const params = new URLSearchParams(window.location.hash.slice(1)); new URLSearchParams(window.location.search).forEach((v, k) => params.set(k, v)); return params; } // 1. Social buttons: come back to this page, with the parameters in the QUERY // string (a fragment is refused, because a server redirect can't carry it). function socialLoginURL(provider) { const params = authorizeParams(); const back = `${window.location.origin}${window.location.pathname}?${params}`; const query = new URLSearchParams({ redirect_uri: back, // never the client's callback state: params.get('state') ?? '', scope: params.get('scope') ?? 'openid profile email', }); return `/oauth_login/${provider}?${query}`; } // 2. Once a session exists (after any login method), replay to /authorize. // It checks the client's redirect_uri, runs consent and PKCE, and issues the code. function resumeAuthorize() { const params = authorizeParams(); if (params.get('client_id') && params.get('response_type')) { window.location.replace(`/authorize?${params}`); } } document.querySelector('#github').onclick = () => { window.location.href = socialLoginURL('github'); }; ``` ###### Example: updating an older login page If the server logs `social login completed an /authorize request without resuming through /authorize`, the login page is still sending the client's callback. The change is one parameter: ```diff - /oauth_login/github?state=st-123&redirect_uri=https://app.example.org/callback + /oauth_login/github?state=st-123&redirect_uri=https://auth.example.com/app/?client_id=c1&response_type=code&redirect_uri=https://app.example.org/callback&state=st-123&nonce=n-456&… ``` The login page also needs to replay the request to `/authorize` once the session exists (`resumeAuthorize()` above). Password login on such a page usually does this already. ###### Compatibility | You use | What to do | |---|---| | The hosted login page (`/app`) | Nothing. From 2.4.6 the bundled login page sends its own `/app` URL, so social login resumes through `/authorize`. The page is built into the same image as the server, so the two always match | | Your own build of the login page, served by Authorizer at `/app` | Send `redirect_uri` = the page's own `/app` URL with the `/authorize` parameters in the **query string**, then replay to `/authorize` once the session exists ([example](#example-a-customised-login-page)). If it's built on `@authorizerdev/authorizer-react`, `AuthorizerSocialLogin` does this from 2.2.1 | | `/oauth_login` directly, outside `/authorize` (mobile apps, a "Sign in with GitHub" link on your own site) | Nothing. Validation against `--allowed-origins` is unchanged, and the callback still appends `state` (and `code` when one exists) to your `redirect_uri` | **Deprecated:** completing an `/authorize` request by sending `redirect_uri` = the client's callback straight to `/oauth_login`. This was the only option before 2.4.6. It still works when that callback's origin is in `--allowed-origins`, but it skips the consent screen, and the server logs a warning (`social login completed an /authorize request without resuming through /authorize`) each time it is used. A future release will refuse it, with a note in the changelog. If you see that warning, move the login UI to the `/app` URL as described above. #### Token Endpoint **Endpoint:** `POST /oauth/token` **Specs:** [RFC 6749 §3.2](https://www.rfc-editor.org/rfc/rfc6749#section-3.2) | [RFC 7636 §4.6](https://www.rfc-editor.org/rfc/rfc7636#section-4.6) | [RFC 8693](https://www.rfc-editor.org/rfc/rfc8693) Serves four grant types: `authorization_code`, `refresh_token`, `client_credentials`, and `urn:ietf:params:oauth:grant-type:token-exchange`. **Content-Type:** `application/x-www-form-urlencoded` or `application/json` **Response headers:** `Cache-Control: no-store`, `Pragma: no-cache` (RFC 6749 §5.1) **Authorization Code grant:** | Parameter | Required | Notes | | --------------- | -------- | ------------------------------------------------------- | | `grant_type` | Yes | `authorization_code` | | `code` | Yes | The authorization code from `/authorize` | | `code_verifier` | Yes\* | PKCE verifier (43–128 chars) | | `client_id` | Yes | Your client ID | | `client_secret` | Yes\* | Required if `code_verifier` is not provided | \*Either `code_verifier` or `client_secret` is required. Client authentication may be sent as HTTP Basic (`client_secret_basic`), in the form body (`client_secret_post`), or omitted entirely for public clients using PKCE (`none`). Authorization codes expire after **10 minutes** (RFC 6749 §4.1.2 recommendation) and are single-use. If `resource` was present at `/authorize`, it must be echoed here (form field `resource`) and match exactly, or the request is rejected with `invalid_grant`. It is not a token endpoint parameter in its own right — it can only confirm the value already bound to the code. **Refresh Token grant:** | Parameter | Required | Notes | | --------------- | -------- | ---------------------------------------------- | | `grant_type` | Yes | `refresh_token` | | `refresh_token` | Yes | A valid refresh token | | `client_id` | Yes | Your client ID — must match the client the refresh token was originally issued to (enforced via the token's `aud` claim); a mismatch is `invalid_grant` | Refresh tokens are **rotated** on each use — the old one is invalidated and a new one returned. **Reuse detection:** each refresh token carries a stable `family_id`, minted once and carried across every rotation in its lineage. Replaying an already-rotated (dead) token is treated as a breach and revokes only that token's family (the specific session lineage) — other sessions and login methods for the same user are untouched. A same-second double-submit of the immediately preceding token (multi-tab race, retry) is tolerated within a **10-second grace window** and is not treated as reuse; anything older, or a replay after the window, revokes the family. **Success response:** ```json { "access_token": "eyJhbG...", "token_type": "Bearer", "id_token": "eyJhbG...", "expires_in": 1800, "scope": "openid profile email", "refresh_token": "eyJhbG..." } ``` **Client Credentials grant** (RFC 6749 §4.4 — machine/service-account tokens): | Parameter | Required | Notes | | --------------- | -------- | ------------------------------------------------------------------------ | | `grant_type` | Yes | `client_credentials` | | `client_id` | Yes | A `service_account` client from the [client registry](./client-registry) | | `client_secret` | Yes\* | Via HTTP Basic (`client_secret_basic`) or form body (`client_secret_post`) | | `scope` | No | Space-separated subset of the client's `allowed_scopes`. Omitted = full authorized set. Any scope outside the allow-list rejects the whole request with `invalid_scope` | \*Instead of a secret, the client may authenticate with an RFC 7523 `client_assertion` — see [Workload Identity](../enterprise/workload-identity). Presenting more than one authentication method is rejected (RFC 6749 §2.3). Interactive clients (including the reserved boot client) are rejected on this grant with `unauthorized_client`. ```bash curl -s -X POST $AUTHORIZER_URL/oauth/token \ -u "$SERVICE_ACCOUNT_ID:$SERVICE_ACCOUNT_SECRET" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials" \ -d "scope=read:reports" ``` ```json { "access_token": "eyJhbG...", "token_type": "Bearer", "expires_in": 1800, "scope": "read:reports" } ``` No `id_token` and no `refresh_token` are issued — machines re-authenticate on expiry (RFC 6749 §4.4.3). The token's `client_id` claim is the service account's `client_id`; its `aud` is the `resource` when one is sent, otherwise the instance's `--client-id`. See the [Client Registry guide](./client-registry) for the full flow. **Token Exchange grant** (RFC 8693 — delegation only): | Parameter | Required | Notes | | -------------------- | -------- | ------------------------------------------------------------------------ | | `grant_type` | Yes | `urn:ietf:params:oauth:grant-type:token-exchange` | | `subject_token` | Yes | The user's access token (the authority being exercised) | | `subject_token_type` | Yes | `urn:ietf:params:oauth:token-type:access_token` or `...:jwt` | | `actor_token` | Yes | The agent's own access token (delegation-only — omitting it is rejected) | | `actor_token_type` | Yes | Same URNs as `subject_token_type` | | `resource` | Yes | Exactly one (RFC 8707) — 0 or >1 values are rejected | | `scope` | No | Requested down-scope; the result is always the intersection with the subject's scope and the agent's ceiling | The calling client must authenticate as a `service_account` (secret or `client_assertion`). The resulting token is short-lived (5 minutes), audience-bound to `resource`, and carries the nested `act` actor chain. Full semantics, security invariants, and examples: [Token Exchange & Delegation](../enterprise/token-exchange). **Error response:** ```json { "error": "invalid_grant", "error_description": "..." } ``` Standard codes: `invalid_request`, `invalid_client`, `invalid_grant`, `unsupported_grant_type`, `unauthorized_client`, `invalid_scope`. ##### Token claims Two claims name the client a token was issued to: | Claim | Token | Value | Spec | | ----- | ----- | ----- | ---- | | `client_id` | Access token | The client the token was issued to: the requesting client on the authorization code, refresh and implicit flows; the service account on `client_credentials`; the instance's `--client-id` for logins through Authorizer's own login page and GraphQL/REST/gRPC APIs | [RFC 9068 §2.2](https://datatracker.ietf.org/doc/html/rfc9068#section-2.2) | | `azp` | ID token | The client the ID token was issued to. Always equal to the ID token's `aud` | [OIDC Core §2](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) | Read `client_id` rather than `aud` to find out which client requested an access token: when a `resource` indicator is sent (RFC 8707), `aud` is that resource, not the client. Neither claim can be changed by the [custom access token script](./server-config). `client_id` is reserved, so a script that sets it is ignored. `azp` is written into the ID token after the script runs. A script may still set `azp` in the **access token**; Authorizer does not put one there itself. :::note Added in v2.4.8 Before v2.4.8 access tokens from logins and from `client_credentials` had no `client_id` claim (delegated [token-exchange](../enterprise/token-exchange) tokens already had one), and ID tokens had no `azp`. Both are additive: `aud` and every other claim are unchanged, so existing verifiers keep working. ::: #### UserInfo Endpoint **Endpoint:** `GET /userinfo` or `POST /userinfo` **Specs:** [OIDC Core §5.3](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) | [OIDC Core §5.4 (scope-based claim filtering)](https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims) | [RFC 6750 (Bearer Token)](https://www.rfc-editor.org/rfc/rfc6750) Returns claims about the authenticated end-user, **filtered by the scopes encoded in the access token**. Both `GET` and `POST` are accepted per OIDC Core §5.3.1 — either way the access token goes in the `Authorization: Bearer` header (a token in the POST body is not supported). ```bash curl -H "Authorization: Bearer ACCESS_TOKEN" https://your-authorizer.example/userinfo ``` **Scope → claim mapping** (OIDC Core §5.4): | Scope | Claims returned in addition to `sub` | |-----------|-------------------------------------------------------------------------------------------------------------------------------| | `profile` | `name`, `family_name`, `given_name`, `middle_name`, `nickname`, `preferred_username`, `profile`, `picture`, `website`, `gender`, `birthdate`, `zoneinfo`, `locale`, `updated_at` | | `email` | `email`, `email_verified` | | `phone` | `phone_number`, `phone_number_verified` | | `address` | `address` | The `sub` claim is **always** returned per OIDC Core §5.3.2. Claims within a granted scope group are included only when the user actually has a value; unset claims are **omitted**, never emitted as JSON `null` — §5.3.2 permits omission but does not permit a present-but-null claim, and OIDF conformance testing (`oidcc-scope-profile`) enforces this. **Error response (RFC 6750 §3):** ``` HTTP/1.1 401 Unauthorized WWW-Authenticate: Bearer realm="authorizer", error="invalid_token", error_description="The access token is invalid or has expired" ``` #### Token Introspection **Endpoint:** `POST /oauth/introspect` **Spec:** [RFC 7662 (OAuth 2.0 Token Introspection)](https://www.rfc-editor.org/rfc/rfc7662) Used by resource servers and API gateways to validate tokens without re-implementing JWT verification. **Content-Type:** `application/x-www-form-urlencoded` **Response headers:** `Cache-Control: no-store`, `Pragma: no-cache` **Client authentication:** `client_secret_basic` (HTTP Basic) or `client_secret_post` (form body). **Request parameters:** | Parameter | Required | Notes | | ----------------- | -------- | ---------------------------------------------- | | `token` | Yes | The token to introspect | | `token_type_hint` | No | `access_token`, `refresh_token`, or `id_token` (unknown hints are ignored, not rejected) | | `client_id` | Yes | When not using HTTP Basic | | `client_secret` | Yes | When not using HTTP Basic | **Active token response:** ```json { "active": true, "scope": "openid profile email", "client_id": "my-app", "exp": 1712500000, "iat": 1712496400, "sub": "user-uuid", "aud": "my-app", "iss": "https://your-authorizer.example", "token_type": "access_token" } ``` **Inactive token response:** ```json { "active": false } ``` Per RFC 7662 §2.2, the inactive response **never** contains any other fields — no `error`, no `error_description`, no claim leakage. A missing/expired/revoked/wrong-audience token all look identical to the client. #### Token Revocation **Endpoint:** `POST /oauth/revoke` **Spec:** [RFC 7009](https://www.rfc-editor.org/rfc/rfc7009) Revokes a refresh token. Per RFC 7009 §2.2, returns HTTP 200 even for invalid or already-revoked tokens (prevents token scanning). | Parameter | Required | Notes | | ----------------- | -------- | --------------------------------------- | | `token` | Yes | The refresh token to revoke | | `token_type_hint` | No | `refresh_token` or `access_token` | | `client_id` | Yes | Your client ID (or via HTTP Basic) | #### JWKS **Endpoint:** `GET /.well-known/jwks.json` **Spec:** [RFC 7517](https://www.rfc-editor.org/rfc/rfc7517) Public signing keys for JWT verification. Supports RSA (`RS256/384/512`), ECDSA (`ES256/384/512`), and HMAC. **HMAC secrets are never exposed** — the array is empty in HMAC-only configurations. ```json { "keys": [ { "kty": "RSA", "use": "sig", "kid": "Hkyj-Z0Ft7MFEvVmFpFrQIZ8pbRDw0WShlpPURJ5xEc", "alg": "RS256", "n": "...", "e": "AQAB" } ] } ``` Each key's `kid` is its [RFC 7638](https://www.rfc-editor.org/rfc/rfc7638) JWK thumbprint (SHA-256, base64url), and every RSA/ECDSA token Authorizer signs carries the same value in its `kid` header. Verifiers that select the key by `kid` — API gateways, SurrealDB's `DEFINE ACCESS ... WITH JWT URL`, most JWT libraries — therefore find it directly. HMAC tokens carry no `kid`, because their key is never published. Verify tokens against this endpoint rather than a copy of it: the `kid` is derived from the key, so it changes whenever the key does. :::caution Changed in v2.4.8 Before v2.4.8 tokens had no `kid` header, and the JWKS used your client ID as the `kid` (`your-client-id`, plus `your-client-id-secondary` for a secondary key). Verifiers that fetch `/.well-known/jwks.json` need no change. If you **pinned a copy** of the JWKS in a gateway or service config, or **hard-coded the client ID as the `kid`**, switch to fetching this endpoint before upgrading — otherwise tokens issued after the upgrade are rejected by that verifier. ::: ##### Manual key rotation Authorizer supports a zero-downtime manual key-rotation workflow via four optional secondary-key flags: - `--jwt-secondary-type` - `--jwt-secondary-secret` - `--jwt-secondary-private-key` - `--jwt-secondary-public-key` When a secondary key is configured, JWKS publishes **both** public keys, each under its own thumbprint `kid`. The signing path always uses the primary key; verification tries the primary first and falls back to the secondary. Because a key's `kid` comes from the key itself, it stays the same when the key moves from primary to secondary, so verifiers that select keys by `kid` keep accepting outstanding tokens through the swap in step 3. **Rotation workflow:** 1. Operator adds a new key as `--jwt-secondary-*` and restarts 2. JWKS now publishes both keys; both can verify existing tokens 3. Operator swaps: new key becomes primary (`--jwt-*`), old key becomes secondary (`--jwt-secondary-*`), restart 4. Outstanding tokens signed by the now-secondary key keep working 5. After all outstanding tokens expire, operator removes the `--jwt-secondary-*` flags and restarts Automated time-based rotation is a future roadmap item. #### Logout (RP-Initiated) **Endpoint:** `GET /logout` or `POST /logout` **Spec:** [OIDC RP-Initiated Logout 1.0](https://openid.net/specs/openid-connect-rpinitiated-1_0.html) | Parameter | Notes | | --------------------------- | ------------------------------------------------------------------------------------------- | | `post_logout_redirect_uri` | Preferred (OIDC spec name). Must be in `--allowed-origins` | | `redirect_uri` | Legacy alias — accepted as fallback | | `state` | Echoed on the final redirect per §3 | | `id_token_hint` | Proves the request comes from a real authenticated session (CSRF defense for GET) | **GET without `id_token_hint`** renders an HTML confirmation page — the actual session deletion only happens via the subsequent POST. This prevents `` attacks. #### Back-Channel Logout (opt-in) **Spec:** [OIDC Back-Channel Logout 1.0](https://openid.net/specs/openid-connect-backchannel-1_0.html) When the server is started with `--backchannel-logout-uri=https://your-rp.example/bcl`, every successful `/logout` fires a signed `logout_token` JWT via HTTP POST to that URL (fire-and-forget, 5-second timeout). **`logout_token` claims:** - `iss`, `aud`, `iat`, `exp` (+5 minutes), `jti` (UUID) - `sub` (user ID), `sid` (session identifier) - `events`: `{"http://schemas.openid.net/event/backchannel-logout": {}}` - **`nonce` is deliberately absent** (explicitly prohibited by §2.4) The `logout_token` is signed with the same key as ID tokens, so the receiver verifies it via the same JWKS endpoint. Discovery advertises `backchannel_logout_supported: true` when the URI is configured. --- ### PKCE Guide PKCE ([RFC 7636](https://www.rfc-editor.org/rfc/rfc7636)) is required for the authorization code flow and prevents authorization code interception attacks. #### 1. Generate a code verifier A random string of 43–128 characters from `[A-Za-z0-9-._~]`: ```javascript const codeVerifier = generateRandomString(43); ``` ```bash # Bash equivalent openssl rand -base64 48 | tr -d '=+/' | cut -c1-64 ``` #### 2. Create a code challenge ```javascript const hash = await crypto.subtle.digest( "SHA-256", new TextEncoder().encode(codeVerifier), ); const codeChallenge = btoa(String.fromCharCode(...new Uint8Array(hash))) .replace(/\+/g, "-") .replace(/\//g, "_") .replace(/=+$/, ""); ``` ```bash # Bash equivalent printf '%s' "$CODE_VERIFIER" | openssl dgst -binary -sha256 | openssl base64 | tr -d '=' | tr '/+' '_-' ``` :::note plain method If `code_challenge_method` is omitted, Authorizer defaults to `plain` per RFC 7636 §4.2 — the verifier is compared directly to the challenge, no hashing. Always send `code_challenge_method=S256` explicitly; `plain` exists only for spec compliance with clients that can't compute SHA-256. ::: #### 3. Send it on `/authorize` ``` GET /authorize?response_type=code&code_challenge=CHALLENGE&code_challenge_method=S256&... ``` #### 4. Exchange at `/oauth/token` ``` POST /oauth/token grant_type=authorization_code&code=AUTH_CODE&code_verifier=CODE_VERIFIER&client_id=CLIENT_ID ``` --- ### Testing Guide A practical, copy-paste-able checklist for verifying your Authorizer instance works against every OIDC spec it implements. #### Prerequisites ```bash export AUTHORIZER_URL="http://localhost:8080" export CLIENT_ID="your-client-id" export CLIENT_SECRET="your-client-secret" ``` You will need `curl`, `jq`, `openssl`, and a web browser. #### 1. Discovery ```bash curl -s $AUTHORIZER_URL/.well-known/openid-configuration | jq ``` **Check:** `issuer` matches `$AUTHORIZER_URL`; `response_types_supported` contains the hybrid combinations; `introspection_endpoint` is present; `registration_endpoint` is absent unless `--enable-dynamic-client-registration` is set; `backchannel_logout_supported` is `true` iff the flag is set. #### 2. JWKS ```bash curl -s $AUTHORIZER_URL/.well-known/jwks.json | jq ``` **Check:** HTTP 200; RSA/ECDSA keys include `kty`, `alg`, `kid`, `use: "sig"`; HMAC-only configs return `keys: []`; multi-key configs return two keys with distinct `kid`s. #### 3. Authorization Code + PKCE (end-to-end) ```bash # 1. Generate verifier + challenge CODE_VERIFIER=$(openssl rand -base64 48 | tr -d '=+/' | cut -c1-64) CODE_CHALLENGE=$(printf '%s' "$CODE_VERIFIER" | openssl dgst -binary -sha256 | openssl base64 | tr -d '=' | tr '/+' '_-') STATE=$(openssl rand -hex 16) # 2. Print the URL to open in a browser echo "$AUTHORIZER_URL/authorize?client_id=$CLIENT_ID&response_type=code&redirect_uri=http://localhost:3000/callback&scope=openid%20profile%20email%20offline_access&state=$STATE&code_challenge=$CODE_CHALLENGE&code_challenge_method=S256&response_mode=query" ``` After logging in and copying the `code` from the redirect: ```bash CODE="paste-code-here" curl -s -X POST $AUTHORIZER_URL/oauth/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=authorization_code" \ -d "code=$CODE" \ -d "code_verifier=$CODE_VERIFIER" \ -d "client_id=$CLIENT_ID" \ -d "redirect_uri=http://localhost:3000/callback" | jq ``` **Check:** - HTTP 200 with `Cache-Control: no-store` header - Response contains `access_token`, `id_token`, `refresh_token`, `token_type: "Bearer"`, `expires_in`, `scope` - ID token payload (decode via [jwt.io](https://jwt.io)) contains: `iss`, `aud`, `azp` (equal to `aud`), `sub`, `exp`, `iat`, `auth_time`, `amr`, `acr="0"`, `at_hash`, and `nonce` if supplied - Access token payload contains `client_id` equal to `$CLIENT_ID` **Verify `at_hash` manually:** ```bash ACCESS_TOKEN="paste-access-token-here" printf '%s' "$ACCESS_TOKEN" | openssl dgst -binary -sha256 | head -c 16 | openssl base64 | tr -d '=' | tr '/+' '_-' ``` Must equal the `at_hash` claim in the ID token. **Refresh the token:** ```bash REFRESH_TOKEN="paste-refresh-token-here" curl -s -X POST $AUTHORIZER_URL/oauth/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=refresh_token" \ -d "refresh_token=$REFRESH_TOKEN" \ -d "client_id=$CLIENT_ID" | jq ``` **Check:** new tokens returned; the new refresh token differs from the old; the old refresh token no longer works (rotation). **Revoke the refresh token:** ```bash curl -s -o /dev/null -w "%{http_code}\n" -X POST $AUTHORIZER_URL/oauth/revoke \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "token=$REFRESH_TOKEN" \ -d "client_id=$CLIENT_ID" \ -d "token_type_hint=refresh_token" # Must print 200 ``` #### 4. UserInfo scope filtering ```bash curl -s -H "Authorization: Bearer $ACCESS_TOKEN" $AUTHORIZER_URL/userinfo | jq ``` Run the authorization code flow three times with different scope sets and observe: - `scope=openid` → response is `{"sub": "..."}` - `scope=openid email` → adds `email`, `email_verified` - `scope=openid profile email` → adds the full profile claim group #### 5. Token Introspection ```bash curl -s -u "$CLIENT_ID:$CLIENT_SECRET" -X POST $AUTHORIZER_URL/oauth/introspect \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "token=$ACCESS_TOKEN" | jq ``` **Check:** active token returns `active: true` + full claim set. Invalid token returns **exactly** `{"active": false}` with no leakage. Wrong client secret via HTTP Basic returns 401 with `WWW-Authenticate: Basic`. #### 6. Hybrid flow ```bash # This MUST be rejected (query mode forbidden for hybrid per OIDC Core §3.3.2.5) curl -sG $AUTHORIZER_URL/authorize \ --data-urlencode "client_id=$CLIENT_ID" \ --data-urlencode "response_type=code id_token" \ --data-urlencode "response_mode=query" \ --data-urlencode "state=$STATE" \ --data-urlencode "code_challenge=$CODE_CHALLENGE" | jq # {"error": "invalid_request", ...} ``` Full hybrid flow via browser: ``` $AUTHORIZER_URL/authorize?client_id=$CLIENT_ID&response_type=code%20id_token&redirect_uri=http://localhost:3000/callback&scope=openid%20profile%20email&state=$STATE&nonce=N&code_challenge=$CODE_CHALLENGE&code_challenge_method=S256 ``` **Check:** redirect fragment contains **both** `code=` and `id_token=`; the ID token payload includes a `c_hash` claim (OIDC Core §3.3.2.11). #### 7. Authorization request parameters - **`prompt=none` with no session** must redirect with `error=login_required` (not render the login UI) - **`prompt=login` with a session** bypasses the session cookie and shows the login UI - **`max_age=0`** is equivalent to `prompt=login` - **`login_hint=alice@example.com`** pre-fills the email field #### 8. Back-channel logout Start a local receiver and set `--backchannel-logout-uri` pointed at it: ```bash # Terminal 1: receiver python3 -c " from http.server import BaseHTTPRequestHandler, HTTPServer import urllib.parse, base64, json class H(BaseHTTPRequestHandler): def do_POST(self): body = self.rfile.read(int(self.headers['Content-Length'])).decode() form = urllib.parse.parse_qs(body) payload = form['logout_token'][0].split('.')[1] payload += '=' * (-len(payload) % 4) print(json.dumps(json.loads(base64.urlsafe_b64decode(payload)), indent=2)) self.send_response(200); self.end_headers() HTTPServer(('127.0.0.1', 9999), H).serve_forever() " # Terminal 2: start Authorizer with --backchannel-logout-uri=http://127.0.0.1:9999/bcl # Terminal 3: sign in through the dashboard, then log out ``` **Check in receiver output:** `iss`, `aud`, `sub`, `sid`, `jti`, `iat`, `exp`, `events` containing the BCL event key, and — critically — `nonce` is **absent**. #### 9. Social SSO providers 1. Register the provider on its console (Google, GitHub, etc.), using `$AUTHORIZER_URL/oauth_callback/` as the callback 2. Configure the provider in Authorizer: `--google-client-id`, `--google-client-secret`, etc. 3. Restart Authorizer — the login page auto-shows the new button 4. Test: visit `$AUTHORIZER_URL/oauth_login/google?redirect_uri=http://localhost:3000/callback&state=$STATE` 5. Verify the resulting ID token has `amr: ["fed"]` (federated authentication) 6. Test social login inside an authorization request (2.4.6+): open the authorization-code URL from [step 3](#3-authorization-code--pkce-end-to-end) in a browser, choose the provider on the login page, and check that: - the `/oauth_login` request's `redirect_uri` is `$AUTHORIZER_URL/app?…`, not your callback (browser dev tools, Network tab); - you land on your callback with `?code=…&state=…`, after the consent screen for a self-registered client; - the ID token from `/oauth/token` carries the `nonce` you sent. See [the full round trip](#example-the-full-round-trip) for the expected requests. #### 10. Automated conformance testing For pre-production validation, run a full OIDC conformance suite: - **[OpenID Foundation Conformance Suite](https://openid.net/certification/instructions/)** — gold-standard; run the **Basic OP**, **Hybrid OP**, and **Introspection** test profiles. - **[oidcdebugger.com](https://oidcdebugger.com/)** — lightweight in-browser authorization endpoint test harness. - **[jwt.io](https://jwt.io)** — decode and verify ID tokens against your JWKS. --- ### Common Issues | Symptom | Likely cause | |---------------------------------------------------|----------------------------------------------------------------------------------------------------| | `invalid_grant` on `/oauth/token` | Code already used, expired, or `code_verifier` doesn't match the original `code_challenge` | | `invalid_request` on `/authorize` | Missing `state`; or `response_mode=query` with a hybrid `response_type` (forbidden by OIDC Core §3.3.2.5) | | `/userinfo` returns only `{"sub":"..."}` | Working as designed — request `scope=openid profile email` to receive profile and email claims | | `unsupported_response_type` | `response_type` value not in the discovery document's `response_types_supported` | | ID token signature verification fails | JWKS returns a different key than the one used to sign. Check `--jwt-type` and key configuration | | Social login callback shows `state mismatch` | Cookies blocked, third-party-cookie restrictions, or session cookie expired between redirects | | Back-channel logout never fires | `--backchannel-logout-uri` not set, or receiver unreachable within 5 seconds | | Auth0 Enterprise OIDC connection can't discover | Wrong Issuer URL — must be exactly `https://your-authorizer.example` (no trailing slash, no path) | | `redirect_uri` rejected | Not in `--allowed-origins`. The debug-level log message names the exact URI that was rejected | | Social login returns `{"error":"invalid redirect uri"}` for a client whose callback is on another origin, while password login works | Before 2.4.6, `/oauth_login` checked the client's callback against `--allowed-origins`. Upgrade to 2.4.6 or later, where social login returns to `/app` and `/authorize` checks the client's registered redirect URIs — see [Social login inside an authorization request](#social-login-inside-an-authorization-request). Don't add the client's origin to `--allowed-origins` as a workaround | | Server logs `social login completed an /authorize request without resuming through /authorize` | A login UI is sending the client's callback straight to `/oauth_login` — a deprecated path that skips consent. Point it at its own `/app` URL instead (see the same section) | | RP reports "unexpected ID Token nonce claim value" | The `nonce` sent to `/authorize` didn't round-trip into the ID token. A custom login UI must forward `nonce` (and the PKCE params) back to `/authorize` after authentication | | `form_post` blocked: "sending form data violates Content Security Policy" | A reverse proxy in front of Authorizer is injecting its own CSP header, overriding the `form_post` CSP Authorizer sets | ### Debugging Tips - **Always check the discovery endpoint first.** Almost every OIDC problem is a configuration mismatch and discovery is the cheapest place to spot it. - **Decode your tokens** at [jwt.io](https://jwt.io) before debugging further — the claims tell you a lot. - **Enable debug logging** with `--log-level=debug` to see every OIDC decision, including which scope groups were filtered out of `/userinfo` and why a `prompt=none` request returned `login_required`. - **Verify clock skew.** If `exp` or `iat` validation is failing, ensure your server and client clocks are within 60 seconds. - **Audit `--allowed-origins`.** `/authorize` rejects unknown `redirect_uri` values with `invalid_request`. --- ## Rate Limiting Authorizer includes built-in per-IP rate limiting to protect authentication endpoints from brute-force attacks and abuse. Rate limiting is always enabled by default with sensible defaults, and supports multi-replica deployments via Redis. ### How it works Every incoming request is tracked by client IP address. Each IP is allowed a sustained request rate (`--rate-limit-rps`) with a burst allowance (`--rate-limit-burst`). When an IP exceeds the limit, Authorizer responds with `429 Too Many Requests` and a `Retry-After` header. **Single instance:** Rate limits are tracked in memory using a token bucket algorithm. No external dependencies required. **Multi-replica:** When Redis is configured (`--redis-url`), rate limits are shared across all replicas using an atomic Redis sliding-window counter (Lua script). This ensures consistent enforcement regardless of which replica handles the request. > **Fail-open behavior (default):** If Redis becomes temporarily unavailable, the rate limiter allows requests through rather than blocking legitimate users. Auth availability takes priority over rate limiting. Set **`--rate-limit-fail-closed=true`** if you prefer **`503`** responses when the rate-limit backend errors (stricter, can block traffic during Redis outages). --- ### CLI Flags | Flag | Default | Description | |------|---------|-------------| | `--rate-limit-rps` | `30` | Maximum sustained requests per second per IP | | `--rate-limit-burst` | `20` | Maximum burst size per IP (allows short spikes above the sustained rate) | | `--rate-limit-fail-closed` | `false` | If `true`, rate-limit backend errors return **503** instead of allowing the request | ```bash ./authorizer \ --rate-limit-rps=30 \ --rate-limit-burst=20 ``` #### Customizing limits For high-traffic deployments, increase the limits: ```bash ./authorizer \ --rate-limit-rps=50 \ --rate-limit-burst=100 ``` For stricter protection (e.g., a small internal deployment): ```bash ./authorizer \ --rate-limit-rps=5 \ --rate-limit-burst=10 ``` #### Disabling rate limiting If your infrastructure already provides rate limiting (e.g., API gateway, CDN, or load balancer), you can disable it: ```bash ./authorizer \ --rate-limit-rps=0 ``` --- ### Exempt endpoints The following endpoints are **not** rate limited because they are infrastructure, static assets, or standards-required discovery endpoints: | Path | Reason | |------|--------| | `/` | Root/info endpoint | | `/health` | Kubernetes liveness probe | | `/healthz` | Kubernetes liveness probe | | `/readyz` | Kubernetes readiness probe | | `/.well-known/openid-configuration` | OIDC discovery (cacheable, spec-required) | | `/.well-known/jwks.json` | JWKS endpoint (cacheable, spec-required) | | `/app/*` | Static frontend assets (login UI) | | `/dashboard/*` | Static frontend assets (admin UI) | All other endpoints are rate limited, including: - **`/metrics`** is not on the main HTTP router; it is on a **dedicated** listener with **no** Gin middleware (use a reasonable `scrape_interval` anyway). - `/playground` (GraphQL playground) - `/graphql` (all auth mutations: signup, login, reset password, etc.) - `/oauth/token` (token exchange) - `/oauth/revoke` (token revocation) - `/oauth_login/:provider` and `/oauth_callback/:provider` (OAuth flows) - `/authorize` (OAuth2 authorize) - `/userinfo` (token-based user info) - `/verify_email` (email verification) - `/logout` (session termination) --- ### Rate limit response When a client exceeds the rate limit, Authorizer returns: ``` HTTP/1.1 429 Too Many Requests Retry-After: 1 Content-Type: application/json { "error": "rate_limit_exceeded", "error_description": "Too many requests. Please try again later." } ``` The `Retry-After: 1` header tells clients to wait at least 1 second before retrying (per [RFC 6585](https://www.rfc-editor.org/rfc/rfc6585#section-4)). --- ### Multi-replica setup with Redis For deployments with multiple Authorizer replicas, configure Redis to ensure rate limits are shared: ```bash ./authorizer \ --redis-url=redis://user:pass@redis-host:6379/0 \ --rate-limit-rps=30 \ --rate-limit-burst=20 ``` When `--redis-url` is set, Authorizer automatically uses Redis for both session storage **and** rate limiting. No additional configuration is needed. #### Redis Cluster Redis Cluster is also supported. Provide multiple URLs: ```bash ./authorizer \ --redis-url="redis://node1:6379,node2:6380,node3:6381" ``` #### Docker Compose example ```yaml services: authorizer: image: quay.io/authorizer/authorizer:latest command: - --database-type=postgres - --database-url=postgres://user:pass@db:5432/authorizer - --url=https://auth.example.com - --encryption-key=your-encryption-key - --jwt-type=HS256 - --jwt-secret=your-jwt-secret - --admin-secret=your-admin-secret - --redis-url=redis://redis:6379 - --rate-limit-rps=30 - --rate-limit-burst=20 - --client-id=YOUR_CLIENT_ID - --client-secret=YOUR_CLIENT_SECRET ports: - "8080:8080" depends_on: - db - redis deploy: replicas: 3 redis: image: redis:7-alpine ports: - "6379:6379" db: image: postgres:15 environment: POSTGRES_USER: user POSTGRES_PASSWORD: pass POSTGRES_DB: authorizer ``` --- ### Monitoring rate limits Rate limit rejections appear in Authorizer's HTTP metrics: ```promql # Rate of 429 responses (rate-limited requests) rate(authorizer_http_requests_total{status="429"}[5m]) # Rate-limited requests by path sum(rate(authorizer_http_requests_total{status="429"}[5m])) by (path) ``` #### Alerting example ```yaml groups: - name: authorizer-rate-limit rules: - alert: HighRateLimitRate expr: rate(authorizer_http_requests_total{status="429"}[5m]) > 1 for: 5m labels: severity: warning annotations: summary: "High rate of rate-limited requests" description: "More than 1 req/sec being rate-limited for 5 minutes. Possible attack or misconfigured client." ``` See [Metrics & Monitoring](./metrics-monitoring) for the full metrics reference. --- ## REST API Alongside the [GraphQL API](./graphql-api), every Authorizer operation is also exposed as a plain **JSON-over-HTTP REST endpoint** under the `/v1/` prefix. The REST surface is generated from the same gRPC service definition via [grpc-gateway](https://github.com/grpc-ecosystem/grpc-gateway), so each REST endpoint maps one-to-one to a GraphQL query/mutation and shares the exact same request and response fields. Use REST when a GraphQL client is overkill — server-to-server calls, shell scripts, webhooks, or platforms where a simple `POST` with a JSON body is the path of least resistance. > The same server also speaks **[gRPC](./grpc)** (default port `9091`, set with > `--grpc-port`) and **[GraphQL](./graphql-api)** (`POST /graphql`). All three are backed by > the same service layer, so they behave identically. > **Availability:** the `/v1` REST gateway is mounted only when the gRPC server is enabled > (the default). It mirrors the full public and admin service surface — see > [Available endpoints](#public-api-endpoints) below. Table of Contents - [Base URL & transport](#base-url--transport) - [Authentication](#authentication) - [Session cookies](#session-cookies) - [Public Endpoints](#public-api-endpoints) - [`POST /v1/signup`](#post-v1signup) - [`POST /v1/login`](#post-v1login) - [`POST /v1/magic_link_login`](#post-v1magic_link_login) - [`POST /v1/verify_email`](#post-v1verify_email) - [`POST /v1/resend_verify_email`](#post-v1resend_verify_email) - [`POST /v1/verify_otp`](#post-v1verify_otp) - [`POST /v1/resend_otp`](#post-v1resend_otp) - [`POST /v1/skip_mfa_setup`](#post-v1skip_mfa_setup) - [`POST /v1/lock_mfa`](#post-v1lock_mfa) - [`POST /v1/email_otp_mfa_setup`](#post-v1email_otp_mfa_setup) - [`POST /v1/sms_otp_mfa_setup`](#post-v1sms_otp_mfa_setup) - [`POST /v1/forgot_password`](#post-v1forgot_password) - [`POST /v1/reset_password`](#post-v1reset_password) - [`POST /v1/logout`](#post-v1logout) - [`GET /v1/profile`](#get-v1profile) - [`POST /v1/update_profile`](#post-v1update_profile) - [`POST /v1/deactivate_account`](#post-v1deactivate_account) - [`POST /v1/session`](#post-v1session) - [`POST /v1/revoke`](#post-v1revoke) - [`POST /v1/validate_jwt_token`](#post-v1validate_jwt_token) - [`POST /v1/validate_session`](#post-v1validate_session) - [`GET /v1/meta`](#get-v1meta) - [`POST /v1/check_permissions`](#post-v1check_permissions) - [`POST /v1/list_permissions`](#post-v1list_permissions) - [Authorizer Admin API Endpoints](#authorizer-admin-api-endpoints) - [Admin Authentication](#admin-authentication) - [`POST /v1/admin/login`](#post-v1adminlogin) - [`POST /v1/admin/logout`](#post-v1adminlogout) - [`GET /v1/admin/session`](#get-v1adminsession) - [`GET /v1/admin/meta`](#get-v1adminmeta) - [Users](#users) - [`POST /v1/admin/users`](#post-v1adminusers) - [`POST /v1/admin/user`](#post-v1adminuser) - [`POST /v1/admin/update_user`](#post-v1adminupdate_user) - [`POST /v1/admin/delete_user`](#post-v1admindelete_user) - [`POST /v1/admin/verification_requests`](#post-v1adminverification_requests) - [Access Control](#access-control) - [`POST /v1/admin/revoke_access`](#post-v1adminrevoke_access) - [`POST /v1/admin/enable_access`](#post-v1adminenable_access) - [`POST /v1/admin/invite_members`](#post-v1admininvite_members) - [Webhooks](#webhooks) - [`POST /v1/admin/add_webhook`](#post-v1adminadd_webhook) - [`POST /v1/admin/update_webhook`](#post-v1adminupdate_webhook) - [`POST /v1/admin/delete_webhook`](#post-v1admindelete_webhook) - [`POST /v1/admin/webhook`](#post-v1adminwebhook) - [`POST /v1/admin/webhooks`](#post-v1adminwebhooks) - [`POST /v1/admin/webhook_logs`](#post-v1adminwebhook_logs) - [`POST /v1/admin/test_endpoint`](#post-v1admintest_endpoint) - [Email Templates](#email-templates) - [`POST /v1/admin/add_email_template`](#post-v1adminadd_email_template) - [`POST /v1/admin/update_email_template`](#post-v1adminupdate_email_template) - [`POST /v1/admin/delete_email_template`](#post-v1admindelete_email_template) - [`POST /v1/admin/email_templates`](#post-v1adminemail_templates) - [Audit Logs](#audit-logs) - [`POST /v1/admin/audit_logs`](#post-v1adminaudit_logs) - [Authorization (FGA)](#authorization-fga) - [`GET /v1/admin/fga/model`](#get-v1adminfgamodel) - [`POST /v1/admin/fga/model`](#post-v1adminfgamodel) - [`POST /v1/admin/fga/tuples`](#post-v1-admin-fga-tuples) - [`POST /v1/admin/fga/tuples/delete`](#post-v1adminfgatuplesdelete) - [`POST /v1/admin/fga/tuples/read`](#post-v1adminfgatuplesread) - [`POST /v1/admin/fga/list_users`](#post-v1adminfgalist_users) - [`POST /v1/admin/fga/expand`](#post-v1adminfgaexpand) - [`POST /v1/admin/fga/reset`](#post-v1adminfgareset) - [Client Registry](#client-registry) - [Trusted Issuers](#trusted-issuers) - [SAML IdP](#saml-idp) - [Errors](#errors) - [See also](#see-also) ### Base URL & transport | Property | Value | | --------------- | --------------------------------------------------------------------- | | Base path | `/v1` | | HTTP port | `--http-port` (default `8080`) | | Content type | `application/json` for request and response bodies | | Field casing | `snake_case` (proto field names), matching the GraphQL field names | | Request bodies | Flat JSON object — the RPC request message fields at the top level (no wrapper) | | gRPC port | `--grpc-port` (default `9091`) — same operations over native gRPC | So if your instance is at `https://auth.example.com`, the permission-check endpoint is `https://auth.example.com/v1/check_permissions`. ### Authentication Authenticated endpoints accept the user's credentials in either of two ways — exactly as the GraphQL API does: - **Bearer token** — `Authorization: Bearer ` - **Session cookie** — see [Session cookies](#session-cookies) below ```bash curl -X GET https://auth.example.com/v1/profile \ -H "Authorization: Bearer $ACCESS_TOKEN" ``` Super-admin endpoints live under `/v1/admin/*` (see [Authorizer Admin API Endpoints](#authorizer-admin-api-endpoints)). They accept the same two mechanisms as GraphQL admin calls: `x-authorizer-admin-secret` or the `authorizer-admin` HTTP-only session cookie set by `POST /v1/admin/login`. #### Session cookies Cookie-based auth works the same over REST as over GraphQL. On successful auth the server returns real `Set-Cookie` response headers (not `Grpc-Metadata-Set-Cookie`). Browser clients should send `credentials: 'include'` on `fetch` (or the equivalent in your HTTP client) so the cookie is stored and resent automatically. | Cookie name | Set by | Purpose | | ----------- | ------ | ------- | | `cookie_session`, `cookie_session_domain` | `signup`, `login`, `session`, `verify_email`, `verify_otp` | App session pair (HTTP-only; host-scoped + domain-scoped) | | `mfa` | `login`, `forgot_password`, `resend_otp` when MFA is required | Short-lived MFA challenge session | | `authorizer-admin` | `POST /v1/admin/login`, `GET /v1/admin/session` | Super-admin session | **Browser example** — login and call an authenticated endpoint with the session cookie: ```javascript // 1. Login — browser stores Set-Cookie automatically await fetch('https://auth.example.com/v1/login', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'jane@example.com', password: 'Test@123' }), }); // 2. Subsequent calls — cookie sent automatically const profile = await fetch('https://auth.example.com/v1/profile', { credentials: 'include', }); ``` **curl example** — capture cookies in a jar and reuse them: ```bash curl -c cookies.txt -X POST https://auth.example.com/v1/login \ -H "Content-Type: application/json" \ -d '{ "email": "jane@example.com", "password": "Test@123" }' curl -b cookies.txt https://auth.example.com/v1/profile ``` Server-side REST clients that are not behind a browser should forward the `Cookie` header on authenticated calls, or use a bearer token from the `access_token` field in the JSON response body instead. > **CSRF note:** From `v2.3.0` onward, state-changing `POST` requests are rejected with > `403` unless they carry an `Origin` (or `Referer`) header. Browsers send this > automatically; server-side clients should set `Origin` explicitly. The official SDKs do > this for you. ### Public API Endpoints Every endpoint below accepts/returns the same fields as its GraphQL counterpart. For the full field-by-field breakdown of each request and response, follow the linked anchor in the [GraphQL API reference](./graphql-api). > **Response shape — no envelope wrapper.** Each endpoint returns the bare domain object, > byte-identical to the GraphQL response. `signup`, `login`, `verify_email`, `verify_otp`, > and `session` return the `AuthResponse` fields at the top level > (`{ "message", "access_token", "id_token", "refresh_token", "expires_in", "user", … }`) — > **not** wrapped under an `auth` key. `profile` returns the `User` object directly (not > under `user`) and `meta` returns the `Meta` object directly (not under `meta`). The > remaining endpoints return `{ "message": "…" }` (or their documented fields). > > Example — `POST /v1/login` response (flat `AuthResponse`): > > ```json > { > "message": "Logged in successfully", > "access_token": "eyJhbGciOiJIUzI1NiIs…", > "expires_in": 1718534400, > "id_token": "eyJhbGciOiJIUzI1NiIs…", > "refresh_token": "…", > "user": { > "id": "…", > "email": "jane@example.com", > "roles": ["user"] > } > } > ``` > > Example — `GET /v1/profile` response (flat `User`): > > ```json > { > "id": "…", > "email": "jane@example.com", > "roles": ["user"], > "given_name": "Jane" > } > ``` #### `POST /v1/signup` Register a new user. Request/response fields match [`signup`](./graphql-api#signup). #### `POST /v1/login` Authenticate with email/phone + password. Returns tokens, or an MFA challenge flag (`should_show_email_otp_screen` / `should_show_totp_screen`) when OTP/[TOTP](https://datatracker.ietf.org/doc/html/rfc6238) is enabled. Mirrors [`login`](./graphql-api#login). ```bash curl -X POST https://auth.example.com/v1/login \ -H "Content-Type: application/json" \ -d '{ "email": "jane@example.com", "password": "Test@123", "scope": ["openid", "profile", "email"] }' ``` #### `POST /v1/magic_link_login` Start a passwordless login; emails a magic link. Mirrors [`magic_link_login`](./graphql-api#magic_link_login). #### `POST /v1/verify_email` Complete email verification using the token from the verification email. Mirrors [`verify_email`](./graphql-api#verify_email). #### `POST /v1/resend_verify_email` Re-send the email-verification message. Mirrors [`resend_verify_email`](./graphql-api#resend_verify_email). #### `POST /v1/verify_otp` Complete an MFA challenge by submitting the email/phone OTP. Mirrors [`verify_otp`](./graphql-api#verify_otp). #### `POST /v1/resend_otp` Re-send the MFA OTP. Mirrors [`resend_otp`](./graphql-api#resend_otp). #### `POST /v1/skip_mfa_setup` Completes an in-progress, token-withheld MFA offer by recording an explicit decline, then issues the withheld access token. Rejected when MFA is org-enforced (`--enforce-mfa`). Mirrors [`skip_mfa_setup`](./graphql-api#skip_mfa_setup). #### `POST /v1/lock_mfa` Records that the caller lost access to their only MFA factor(s); only allowed with no verified Email/SMS OTP fallback enrolled. Does not issue a token — the account requires admin recovery afterward. Mirrors [`lock_mfa`](./graphql-api#lock_mfa). #### `POST /v1/email_otp_mfa_setup` Sends a one-time code to the caller's own email and creates an unverified email-OTP MFA enrollment — either for an already-authenticated caller adding a second factor, or a caller in the withheld first-time-offer state identified by the MFA session cookie. Mirrors [`email_otp_mfa_setup`](./graphql-api#email_otp_mfa_setup). #### `POST /v1/sms_otp_mfa_setup` Same as `email_otp_mfa_setup`, for SMS. Mirrors [`sms_otp_mfa_setup`](./graphql-api#sms_otp_mfa_setup). #### `POST /v1/totp_mfa_setup` Generates a fresh TOTP secret, QR image, and recovery codes for the caller to enroll as an MFA method. Nothing is sent anywhere — the enrollment payload is returned directly, and enrollment is completed with `verify_otp` (`is_totp: true`). Mirrors [`totp_mfa_setup`](./graphql-api#totp_mfa_setup). #### `POST /v1/webauthn_registration_options` Returns the [WebAuthn](https://www.w3.org/TR/webauthn-2/) creation options (an opaque JSON string) to hand to `navigator.credentials.create()`. Works for an already-authenticated caller adding a passkey, or for a caller in the withheld first-time MFA-offer state identified by the MFA session cookie. #### `POST /v1/webauthn_registration_verify` Submits the credential produced by the browser to finish registration. Returns the full auth response: on the MFA-session-cookie path this also completes the gate and issues the withheld access token; on the ordinary authenticated path `access_token` is null. #### `POST /v1/webauthn_login_options` Returns the WebAuthn request options for `navigator.credentials.get()`. Omit `email` for the usernameless (discoverable credential) ceremony. #### `POST /v1/webauthn_login_verify` Submits the signed assertion to complete passkey login and issue tokens. #### `POST /v1/webauthn_credentials` Lists the authenticated caller's own registered passkeys. Requires authentication. #### `POST /v1/webauthn_delete_credential` Deletes one of the authenticated caller's own passkeys by id. Requires authentication. #### `POST /v1/forgot_password` Start password reset; emails a reset link. Mirrors [`forgot_password`](./graphql-api#forgot_password). #### `POST /v1/reset_password` Set a new password using the reset token. Mirrors [`reset_password`](./graphql-api#reset_password). #### `POST /v1/logout` Invalidate the current session *(auth)*. Mirrors [`logout`](./graphql-api#logout). #### `GET /v1/profile` Get the authenticated user's profile *(auth)*. Mirrors [`profile`](./graphql-api#profile). #### `POST /v1/update_profile` Update the authenticated user's profile *(auth)*. Mirrors [`update_profile`](./graphql-api#update_profile). #### `POST /v1/deactivate_account` Deactivate (soft-delete) the authenticated user's account *(auth)*. Mirrors [`deactivate_account`](./graphql-api#deactivate_account). #### `POST /v1/session` Refresh / fetch the current session *(auth)*. Mirrors [`session`](./graphql-api#session). #### `POST /v1/revoke` Revoke a refresh token. Mirrors [`revoke`](./graphql-api#revoke). #### `POST /v1/validate_jwt_token` Validate a JWT and, optionally, required relations. Mirrors [`validate_jwt_token`](./graphql-api#validate_jwt_token). #### `POST /v1/validate_session` Validate a session cookie and required relations. Mirrors [`validate_session`](./graphql-api#validate_session). #### `GET /v1/meta` Server feature flags & provider availability. Mirrors [`meta`](./graphql-api#meta). #### `POST /v1/check_permissions` Answer authorization questions against the embedded [FGA (ReBAC) engine](./authorization) — evaluate one or more permission checks in a single call. At least one, at most **100** checks. `results` come back in the same order as `checks` and echo each pair. The subject is pinned server-side from the caller's token/cookie; the optional `user` field is honored only for super-admins or when it equals the caller's own subject. **Request body** | Field | Type | Description | Required | | -------- | -------------------------- | ------------------------------------------------------------------------------------------------ | -------- | | `checks` | `PermissionCheckInput[]` | Each `{ relation, object, contextual_tuples? }`. 1–100 entries. | yes | | `user` | `string` | Explicit subject (`type:id`, or a bare id treated as `user:`). Super-admin / self only. | no | `contextual_tuples` are extra `{ user, relation, object }` tuples evaluated for that one check only and never persisted — useful for "what-if" checks and request-time facts. ```bash curl -X POST https://auth.example.com/v1/check_permissions \ -H "Authorization: Bearer $ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "checks": [ { "relation": "can_view", "object": "document:1" }, { "relation": "can_edit", "object": "document:1" } ] }' ``` ```json { "results": [ { "relation": "can_view", "object": "document:1", "allowed": true }, { "relation": "can_edit", "object": "document:1", "allowed": false } ] } ``` With a contextual tuple: ```bash curl -X POST https://auth.example.com/v1/check_permissions \ -H "Authorization: Bearer $ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "checks": [ { "relation": "can_view", "object": "document:1", "contextual_tuples": [ { "user": "user:alice", "relation": "member", "object": "team:eng" } ] } ] }' ``` #### `POST /v1/list_permissions` List what the subject can access. With both `relation` and `object_type` set it answers "which `object_type`s can I `relation`?"; either or both filters may be omitted, so an empty body returns every permission the subject holds. **Request body** | Field | Type | Description | Required | | ------------- | -------- | ------------------------------------------------------- | -------- | | `relation` | `string` | Optional relation filter (e.g. `can_view`). | no | | `object_type` | `string` | Optional object-type filter (e.g. `document`). | no | | `user` | `string` | Optional explicit subject; same trust rules as above. | no | ```bash curl -X POST https://auth.example.com/v1/list_permissions \ -H "Authorization: Bearer $ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "relation": "can_view", "object_type": "document" }' ``` ```json { "objects": ["document:1", "document:42"], "permissions": [ { "object": "document:1", "relation": "can_view" }, { "object": "document:42", "relation": "can_view" } ], "truncated": false } ``` `truncated` is `true` when the result was capped at **1000** entries and more permissions exist — narrow the query with `relation` / `object_type` to page through them. ### Authorizer Admin API Endpoints All admin endpoints require super-admin authentication via the `x-authorizer-admin-secret` request header or an `authorizer.admin` session cookie (set by `POST /v1/admin/login`). Except `POST /v1/admin/login`, which may be called without an existing session. The operations are grouped by domain below; each mirrors its GraphQL counterpart for request/response fields. > **Note:** Admin operations are available over all three surfaces — REST (below), native gRPC (`AuthorizerAdminService`, see the [gRPC API](./grpc#authorizer-admin-methods)), and the [GraphQL API](./graphql-api) (the `_`-prefixed operations). #### Admin Authentication ##### `POST /v1/admin/login` Authenticate as super-admin with the admin secret. Sets the `authorizer-admin` session cookie via `Set-Cookie` (same as GraphQL `_admin_login`). **Request body** | Field | Type | Description | Required | | --------------- | -------- | ----------------------- | -------- | | `admin_secret` | `string` | The admin secret value. | yes | **Response** `{ message: string }` ##### `POST /v1/admin/logout` Invalidate the current admin session. **Response** `{ message: string }` ##### `GET /v1/admin/session` Verify the current admin session is valid. **Response** `{ message: string }` ##### `GET /v1/admin/meta` Get admin-level metadata about the server (version, feature flags). **Response** — same as [`GET /v1/meta`](#get-v1meta) but with admin-only fields #### Users ##### `POST /v1/admin/users` List all users with pagination and optional search. **Request body** | Field | Type | Description | Required | | ------------ | ------------------- | ------------ | -------- | | `pagination` | `{ page, limit }` | Page & limit. | no | | `query` | `string` | Case-insensitive substring filter (matches against user ID, email, given_name, family_name, nickname). | no | **Response** `{ users: User[], pagination: { page, limit, total, offset } }` ##### `POST /v1/admin/user` Get a specific user by id or email. **Request body** | Field | Type | Description | Required | | ----- | -------- | --------------- | -------- | | `id` | `string` | User id. | no | | `email` | `string` | User email. | no | **Response** `User` ##### `POST /v1/admin/update_user` Update user profile fields (email, roles, name, etc.). **Request body** — see [`_update_user`](./graphql-api#_update_user) for the full field list. **Response** `User` ##### `POST /v1/admin/delete_user` Delete a user by id (and all associated OTP/verification data). **Request body** | Field | Type | Description | Required | | ----- | -------- | ----------- | -------- | | `id` | `string` | User id. | yes | :::warning Breaking in 2.4.0 This took `email` and now takes `id` only — a phone-only account has no email, so it could not be deleted at all. ::: **Response** `{ message: string }` ##### `POST /v1/admin/verification_requests` List pending verification requests (email, phone OTP, etc.) with optional pagination. **Request body** | Field | Type | Description | Required | | ------------ | ----------------- | ------------ | -------- | | `pagination` | `{ page, limit }` | Page & limit. | no | **Response** `{ verification_requests: VerificationRequest[], pagination: { ... } }` #### Access Control ##### `POST /v1/admin/revoke_access` Revoke a user's access (set revoked_timestamp), firing the `user.access_revoked` webhook. **Request body** | Field | Type | Description | Required | | ------- | -------- | ----------- | -------- | | `user_id` | `string` | User id. | yes | **Response** `{ message: string }` ##### `POST /v1/admin/enable_access` Re-enable a previously revoked user (clear revoked_timestamp), firing the `user.access_enabled` webhook. **Request body** | Field | Type | Description | Required | | ------- | -------- | ----------- | -------- | | `user_id` | `string` | User id. | yes | **Response** `{ message: string }` ##### `POST /v1/admin/invite_members` Invite users to the platform by email, sending them an invitation link. **Request body** | Field | Type | Description | Required | | -------------- | ---------- | -------------------------------------- | -------- | | `emails` | `string[]` | Email addresses to invite. | yes | | `redirect_uri` | `string` | Where to redirect after signup. | no | **Response** `{ message: string }` #### Webhooks ##### `POST /v1/admin/add_webhook` Register a new webhook for an event. **Request body** — see [`_add_webhook`](./graphql-api#_add_webhook) for field details. **Response** `{ message: string }` ##### `POST /v1/admin/update_webhook` Update an existing webhook (endpoint, headers, enabled state, etc.). **Request body** — see [`_update_webhook`](./graphql-api#_update_webhook) for field details. **Response** `{ message: string }` ##### `POST /v1/admin/delete_webhook` Delete a webhook by id. **Request body** | Field | Type | Description | Required | | ----- | -------- | ------------ | -------- | | `id` | `string` | Webhook id. | yes | **Response** `{ message: string }` ##### `POST /v1/admin/webhook` Get a webhook by id. **Request body** | Field | Type | Description | Required | | ----- | -------- | ------------ | -------- | | `id` | `string` | Webhook id. | yes | **Response** `Webhook` ##### `POST /v1/admin/webhooks` List all webhooks with pagination. **Request body** | Field | Type | Description | Required | | ------------ | ----------------- | ------------ | -------- | | `pagination` | `{ page, limit }` | Page & limit. | no | **Response** `{ webhooks: Webhook[], pagination: { ... } }` ##### `POST /v1/admin/webhook_logs` List webhook delivery logs with optional pagination and webhook_id filter. **Request body** | Field | Type | Description | Required | | ------------ | ----------------- | -------------- | -------- | | `pagination` | `{ page, limit }` | Page & limit. | no | | `webhook_id` | `string` | Filter by hook. | no | **Response** `{ webhook_logs: WebhookLog[], pagination: { ... } }` ##### `POST /v1/admin/test_endpoint` Send a test webhook payload to an endpoint and return the response. **Request body** | Field | Type | Description | Required | | ------------ | ------------------- | -------------------- | -------- | | `event_name` | `string` | Event to simulate. | yes | | `endpoint` | `string` | URL to call. | yes | | `headers` | `map[string]string` | Extra HTTP headers. | no | **Response** `{ http_status: int, response: string }` #### Email Templates ##### `POST /v1/admin/add_email_template` Create a new email template for an event. **Request body** — see [`_add_email_template`](./graphql-api#_add_email_template) for field details. **Response** `{ message: string }` ##### `POST /v1/admin/update_email_template` Update an email template. **Request body** — see [`_update_email_template`](./graphql-api#_update_email_template) for field details. **Response** `{ message: string }` ##### `POST /v1/admin/delete_email_template` Delete an email template by id. **Request body** | Field | Type | Description | Required | | ----- | -------- | ------------ | -------- | | `id` | `string` | Template id. | yes | **Response** `{ message: string }` ##### `POST /v1/admin/email_templates` List email templates with pagination. **Request body** | Field | Type | Description | Required | | ------------ | ----------------- | ------------ | -------- | | `pagination` | `{ page, limit }` | Page & limit. | no | **Response** `{ email_templates: EmailTemplate[], pagination: { ... } }` #### Audit Logs ##### `POST /v1/admin/audit_logs` Retrieve audit log entries with optional filtering and pagination. **Request body** | Field | Type | Description | Required | | ---------------- | ----------------- | ---------------------------------- | -------- | | `pagination` | `{ page, limit }` | Page & limit. | no | | `actor_id` | `string` | Filter by actor id. | no | | `action` | `string` | Filter by action type. | no | | `resource_type` | `string` | Filter by resource type. | no | | `resource_id` | `string` | Filter by resource id. | no | | `from_timestamp` | `int64` | Filter entries at/after this Unix timestamp. | no | | `to_timestamp` | `int64` | Filter entries at/before this Unix timestamp. | no | **Response** `{ audit_logs: AuditLog[], pagination: { ... } }` #### Authorization (FGA) Manage the embedded fine-grained authorization (FGA) engine: the authorization model and relationship tuples. See [Authorization (FGA)](./authorization) for the conceptual model. ##### `GET /v1/admin/fga/model` Retrieve the active authorization model as FGA DSL. An empty store returns an empty model (not an error). **Response** `{ id: string, dsl: string }` ##### `POST /v1/admin/fga/model` Install a new authorization model version from FGA DSL. Models are versioned and append-only. **Request body** | Field | Type | Description | Required | | ----- | -------- | ----------- | -------- | | `dsl` | `string` | FGA DSL. | yes | **Response** `{ id: string, dsl: string }` ##### `POST /v1/admin/fga/tuples` {#post-v1-admin-fga-tuples} Write (persist) relationship tuples. **Request body** | Field | Type | Description | Required | | ------- | ------------------------- | ------------------- | -------- | | `tuples` | `{ user, relation, object }[]` | Tuples to write. | yes | **Response** `{ message: string }` ##### `POST /v1/admin/fga/tuples/delete` Delete relationship tuples. **Request body** | Field | Type | Description | Required | | ------- | ------------------------- | ------------------- | -------- | | `tuples` | `{ user, relation, object }[]` | Tuples to delete. | yes | **Response** `{ message: string }` ##### `POST /v1/admin/fga/tuples/read` Read stored tuples with optional filtering and pagination. **Request body** | Field | Type | Description | Required | | ------------------- | --------- | ------------------------ | -------- | | `user` | `string` | Filter by user. | no | | `relation` | `string` | Filter by relation. | no | | `object` | `string` | Filter by object. | no | | `page_size` | `int` | Max tuples per page. | no | | `continuation_token`| `string` | Pagination token. | no | **Response** `{ tuples: { user, relation, object }[], continuation_token: string }` ##### `POST /v1/admin/fga/list_users` List fully-qualified user ids that have a relation on an object (reveals the access graph; admin-only). **Request body** | Field | Type | Description | Required | | ---------- | -------- | ---------------------- | -------- | | `object` | `string` | Object to inspect. | yes | | `relation` | `string` | Relation to resolve. | yes | | `user_type`| `string` | Type of users to list. | yes | **Response** `{ users: string[] }` ##### `POST /v1/admin/fga/expand` Expand the relationship/userset tree for a relation on an object (admin-only; useful for debugging). Returns the [OpenFGA](https://openfga.dev) userset tree as a JSON string. **Request body** | Field | Type | Description | Required | | ---------- | -------- | -------------------- | -------- | | `relation` | `string` | Relation to expand. | yes | | `object` | `string` | Object to expand on. | yes | **Response** `{ tree: string }` ##### `POST /v1/admin/fga/reset` Delete the entire fine-grained authorization store (model, all versions, and all tuples) and start fresh. Refused if any tuples still exist. Destructive and audited. **Request body** — empty **Response** `{ message: string }` #### Client Registry Manage machine/workload identity clients. All admin-only. Field-level request/response shapes and examples: [Client Registry guide](./client-registry). | Endpoint | Description | | ---------------------------------------- | --------------------------------------------------------------------- | | `POST /v1/admin/create_client` | Provision a new client; returns the secret exactly once. | | `POST /v1/admin/update_client` | Update name, description, allowed scopes, or active state. | | `POST /v1/admin/delete_client` | Delete a client by id, cascading to its trusted issuers. | | `POST /v1/admin/rotate_client_secret` | Replace the client secret, returned exactly once. | | `POST /v1/admin/client` | Get a single client by id. Secret never surfaced. | | `POST /v1/admin/clients` | List clients with pagination. Secrets never surfaced. | #### Trusted Issuers Manage external JWT issuers for [RFC 7523](https://datatracker.ietf.org/doc/html/rfc7523) `private_key_jwt` client assertions. All admin-only. Field-level request/response shapes: [Workload Identity](../enterprise/workload-identity). | Endpoint | Description | | ------------------------------------------ | --------------------------------------------------------------------- | | `POST /v1/admin/add_trusted_issuer` | Register an issuer for a client (`subject_claim` defaults to `sub`). | | `POST /v1/admin/update_trusted_issuer` | Update name, JWKS URL, expected audience, active state, or [SPIFFE](https://spiffe.io) hint. | | `POST /v1/admin/delete_trusted_issuer` | Delete a trusted issuer by id. | | `POST /v1/admin/trusted_issuer` | Get a single trusted issuer by id. | | `POST /v1/admin/trusted_issuers` | List trusted issuers, optionally filtered by client id. | #### SAML IdP Manage Authorizer acting as a [SAML 2.0](https://www.oasis-open.org/standard/saml/) IdP for downstream service providers, plus IdP signing-key rotation. All admin-only. Field-level request/response shapes: [SAML IdP](../enterprise/saml-idp). | Endpoint | Description | | ------------------------------------------------ | --------------------------------------------------------------------- | | `POST /v1/admin/create_saml_service_provider` | Register a downstream SP. | | `POST /v1/admin/update_saml_service_provider` | Update a downstream SP's name, endpoints, certificate, or mapping. | | `POST /v1/admin/delete_saml_service_provider` | Delete a downstream SP by id. | | `POST /v1/admin/saml_service_provider` | Get a single downstream SP by id. | | `POST /v1/admin/saml_service_providers` | List downstream SPs for an org. | | `POST /v1/admin/rotate_saml_idp_cert` | Generate a new current signing keypair, demoting the previous one. | | `POST /v1/admin/retire_saml_idp_key` | Retire a published-but-not-signing SAML IdP key by id. | | `POST /v1/admin/saml_idp_keys` | List all SAML IdP signing keys for an org. | | `POST /v1/admin/import_saml_sp_metadata` | Parse pasted SP metadata XML; no record created, no remote fetch. | #### Organizations Multi-tenant organizations and their membership. Super-admin, or that organization's own org-admin (the reserved `authorizer:org_admin` role) for the org-scoped operations. Field-level request/response shapes: [Organizations](../enterprise/organizations). | Endpoint | Description | | --------------------------------------- | ----------------------------------------------------------------- | | `POST /v1/admin/create_organization` | Create an organization. Super-admin only. | | `POST /v1/admin/update_organization` | Update name, display name, or enabled state. | | `POST /v1/admin/delete_organization` | Delete an organization and its scoped records. Super-admin only. | | `POST /v1/admin/organization` | Get a single organization by id. | | `POST /v1/admin/organizations` | List organizations. Super-admin only. | | `POST /v1/admin/add_org_member` | Add a user to an organization with a set of org roles. | | `POST /v1/admin/remove_org_member` | Remove a user from an organization. | | `POST /v1/admin/org_members` | List an organization's members. | | `POST /v1/admin/user_organizations` | List the organizations a user belongs to, with their roles. | #### Organization Domains Verified DNS-domain-to-organization mappings used for home-realm discovery — routing a login to the correct tenant IdP. Field-level shapes: [Organization Domains](../enterprise/org-domains). | Endpoint | Description | | ------------------------------------------- | -------------------------------------------------------------------- | | `POST /v1/admin/request_org_domain` | Start domain verification; returns the DNS TXT challenge to publish. | | `POST /v1/admin/verify_org_domain` | Check the published TXT record and mark the domain verified. | | `POST /v1/admin/add_verified_org_domain` | Trusted-assert a domain as verified, skipping DNS. Super-admin only. | | `POST /v1/admin/delete_org_domain` | Remove a mapping; the domain stops routing to that organization. | | `POST /v1/admin/org_domains` | List an organization's domains. | #### Organization SSO Connections Per-organization upstream identity providers an org's members sign in through. The upstream `client_secret` is stored encrypted and never returned. Field-level shapes: [Org SSO (OIDC)](../enterprise/org-sso-oidc) and [Org SAML](../enterprise/org-saml). | Endpoint | Description | | -------------------------------------------------- | -------------------------------------------------- | | `POST /v1/admin/create_org_oidc_connection` | Register an upstream OIDC IdP for an organization. | | `POST /v1/admin/update_org_oidc_connection` | Update an OIDC connection. | | `POST /v1/admin/delete_org_oidc_connection` | Delete an OIDC connection. | | `POST /v1/admin/org_oidc_connection` | Get an OIDC connection by id or org id. | | `POST /v1/admin/create_org_saml_connection` | Register an upstream SAML IdP for an organization. | | `POST /v1/admin/update_org_saml_connection` | Update a SAML connection. | | `POST /v1/admin/delete_org_saml_connection` | Delete a SAML connection. | | `POST /v1/admin/org_saml_connection` | Get a SAML connection by id or org id. | #### SCIM Inbound [SCIM 2.0](https://datatracker.ietf.org/doc/html/rfc7644) provisioning endpoints, one per organization. The bearer token is returned exactly once — at creation and at rotation — and is never retrievable afterwards. Field-level shapes: [SCIM](../enterprise/scim). | Endpoint | Description | | --------------------------------------- | -------------------------------------------------------------------- | | `POST /v1/admin/create_scim_endpoint` | Enable SCIM for an organization; returns the one-time bearer token. | | `POST /v1/admin/rotate_scim_token` | Issue a new token, invalidating the old one. Shown once. | | `POST /v1/admin/delete_scim_endpoint` | Disable SCIM for an organization. | | `POST /v1/admin/scim_endpoint` | Get an organization's SCIM endpoint metadata. Never returns the token. | ### Errors REST errors return a non-`200` HTTP status with a stable JSON envelope: ```json { "code": "failed_precondition", "message": "fga is not enabled on this server" } ``` `code` is a snake_case gRPC status token (for example `invalid_argument`, `unauthenticated`, `permission_denied`, `not_found`, `method_not_allowed`). `message` is a human-readable description. Common cases: | Situation | HTTP status | `code` (typical) | | ------------------------------------------ | ------------------ | ----------------------- | | Missing/invalid credentials | `401 Unauthorized` | `unauthenticated` | | Explicit `user` not permitted for caller | `403 Forbidden` | `permission_denied` | | FGA not enabled (`--fga-store` unset) | `400 Bad Request` | `failed_precondition` | | Validation failure (e.g. `> 100` checks) | `400 Bad Request` | `invalid_argument` | | Wrong HTTP method (e.g. `GET` on `POST`) | `405 Method Not Allowed` | `method_not_allowed` | ### See also - [GraphQL API](./graphql-api) — the full field-level reference shared by all transports. - [gRPC API](./grpc) — the same operations over native gRPC (BSR module, reflection, health). - [Authorization (FGA)](./authorization) — the relationship model behind the permission endpoints. - [Endpoints](./endpoints) — OAuth/OIDC and operational endpoints (`/authorize`, `/oauth/token`, `/.well-known/*`, `/healthz`). - [MCP Server](./mcp) — exposing `check_permissions` / `list_permissions` to LLM agents. --- ## Security Hardening This page documents the security-relevant CLI flags introduced in the April 2026 hardening pass, along with the operational guidance you need to deploy them safely. Most of the hardening is on by default and requires no action; the few breaking changes are flagged at the top. --- ### TL;DR — Breaking changes If you are upgrading from a release **before** the April 2026 security batch, you must address these two items before restarting: 1. **`--admin-secret` is now required.** The previous `"password"` default is gone. Empty (or absent) `--admin-secret` causes the server to exit immediately with a fatal error. Pick any non-empty value; the strength of the secret is your responsibility. ```bash ./authorizer --admin-secret="$(openssl rand -hex 32)" ... ``` 2. **`--trusted-proxies` defaults to none.** Rate limiting, audit logs, and CSRF same-origin checks now key on `RemoteAddr` by default — they ignore `X-Forwarded-For` unless you opt in. If you run Authorizer behind a reverse proxy (nginx, ALB, Cloudflare, an ingress controller), you must list the proxy's network in CIDR form or your metrics and rate limits will be keyed on the proxy IP instead of the real client IP. ```bash ./authorizer \ --trusted-proxies=10.0.0.0/8,127.0.0.1/32 \ ... ``` See [Trusted proxies](#trusted-proxies) below for details. Everything else in this document is opt-in or already on by default. --- ### Admin authentication ```bash ./authorizer \ --admin-secret="$(openssl rand -hex 32)" \ --disable-admin-header-auth=true ``` - **`--admin-secret`** (required, non-empty): the super-admin secret used to authenticate admin operations. The previous insecure `"password"` default is gone — startup fails fast if you forget to set it. Pick any value you trust; the server only enforces non-emptiness. - **`--disable-admin-header-auth`** (default `false`): when `true`, the `X-Authorizer-Admin-Secret` header is no longer accepted as admin authentication; only the secure admin cookie is honoured. **Recommended for production.** --- ### Refresh tokens ```bash ./authorizer --refresh-token-expires-in=2592000 ``` - **`--refresh-token-expires-in`** (default `2592000`, 30 days): refresh token lifetime in seconds. Previously hardcoded to 30 days. Shorten for higher-security deployments where re-authentication is acceptable; lengthen for long-lived sessions where a 30-day window is too short. **Revocation on password reset**: a successful [`reset_password`](./graphql-api#reset_password) synchronously deletes all of the user's existing sessions and refresh tokens from the session store before the mutation returns — any pre-existing session or refresh token is rejected immediately after. This closes the gap where an attacker holding a live session before the reset kept access after it. --- ### Trusted proxies ```bash ./authorizer --trusted-proxies=10.0.0.0/8,127.0.0.1/32 ``` - **`--trusted-proxies`** (default empty, comma-separated CIDRs or bare IPs): list of reverse-proxy networks whose `X-Forwarded-For` / `X-Real-Ip` headers are honoured when computing the client IP. When the list is **empty** (the default), the connection's peer address is used and forwarded headers are ignored entirely, so the client IP cannot be spoofed. When the list contains networks, the `X-Forwarded-For` chain is walked **right-to-left**, past each hop that is itself a trusted proxy, and the first untrusted entry is taken as the client. That is correct whether your proxy *replaces* the header or *appends* to it — the widely-repeated advice to "take the leftmost entry" is spoofable against a proxy that appends, because the leftmost entry is then attacker-supplied. :::caution List every hop With a CDN in front of a load balancer, **both** must appear in the list. The walk stops at the outermost hop you did not list and returns *that* address — a real proxy address rather than a forged one, which is the safe failure, but not the client you wanted. On Railway, use `--trusted-proxies=100.64.0.0/10`. ::: :::note Changed in 2.4.1 This flag has existed since 2.2.1, but until 2.4.1 it only governed Gin's own client-IP resolution — rate limiting and the request log. Audit-log attribution and the admin-secret lockout used a separate resolver that read `X-Forwarded-For` unconditionally, so the "immune to spoofing" property below did **not** hold for them ([GHSA-93hc-xq3w-xw87](https://github.com/authorizerdev/authorizer/security/advisories/GHSA-93hc-xq3w-xw87)). All surfaces — HTTP, REST and gRPC — now share one resolver governed by this flag. If you run behind a proxy and never set it, upgrading to 2.4.1 changes the recorded client IP to the proxy's address; the server logs a warning at startup when the flag is empty. ::: When the list contains CIDRs, Gin trusts forwarded headers from connections originating in those networks. If you run Authorizer behind a reverse proxy you **must** set this flag, otherwise: | Subsystem | Behaviour without `--trusted-proxies` | |---|---| | Per-IP rate limiting | All requests appear to come from the proxy → one rate-limit bucket for the entire fleet → trivial to exhaust. | | Audit logs | Every event is recorded with the proxy IP, not the user's. | | Admin-secret lockout | The brute-force counter buckets on the proxy IP, so one attacker's failed guesses lock out **every** operator for the window. | | CSRF same-origin enforcement | Uses the request `Host` header (unaffected); but combined with the wrong client IP makes investigations harder. | | [Prometheus](https://prometheus.io) metrics | `authorizer_http_requests_total` labelled by proxy IP only. | #### Common deployments | Topology | `--trusted-proxies` value | |---|---| | Single host, no proxy | leave empty | | Behind nginx on the same host | `127.0.0.1/32,::1/128` | | Behind Cloudflare | the [Cloudflare IP ranges](https://www.cloudflare.com/ips/) | | Behind an AWS ALB | the VPC CIDR (e.g. `10.0.0.0/16`) | | Inside a Kubernetes cluster | the pod and service CIDRs (e.g. `10.0.0.0/8`) | --- ### Trusted base URL ```bash ./authorizer --url=https://auth.example.com ``` :::warning Required as of 2.4.0 The server **refuses to start** without `--url`. Deployments upgrading from 2.3.x that never set it will fail to boot until they do — see [Upgrading to 2.4.0](../migration/v1-to-v2#upgrading-from-23x-to-240). ::: - **`--url`** (**required**): the operator-configured canonical base URL of this Authorizer instance. It is the **only** source used to derive the server's own host — verification/reset/magic-link email links, the JWT `iss` claim, and the OIDC discovery/JWKS document URLs — and every request header that could otherwise influence it (`X-Authorizer-URL`, `X-Forwarded-Host`, `Host`) is ignored. The value is normalized to scheme+host (path, query, fragment, userinfo, and trailing slash stripped) and pinned once at startup, before any listener accepts a connection. A value that cannot be normalized — `auth.example.com` with no scheme, or a URL carrying user info — is **rejected at startup** rather than silently ignored, since either would otherwise start in the vulnerable configuration while looking configured. Before 2.4.0 the flag was optional, and leaving it empty fell back to header-based derivation (`X-Authorizer-URL`, then `X-Forwarded-Host`/`Host`). That fallback is a host-header-injection account-takeover surface (CWE-640): a request with a forged host header causes a password-reset or verification email to carry a **genuine** single-use link pointing at an attacker-controlled domain — no prior access and no mailbox compromise required. Making the flag mandatory is the only fix that closes the class; validating the derived host against `--allowed-origins` would help only deployments that configured an explicit list, and would do nothing on the default `*` — which is the configuration the attack targets. This costs no supported capability. Setting `--url` already collapsed an instance to a single canonical host, so serving several hostnames from one instance only ever worked on the vulnerable path. Verified organization domains are email-domain-to-organization routing for home realm discovery, not HTTP virtual hosting, and are unaffected. #### `--url` vs `--allowed-origins` vs the SDKs' `authorizerURL` Three similarly-named settings that mean different things. Confusing `--url` with `--allowed-origins` is the most common misconfiguration: | Setting | Lives in | Names | Example | |---|---|---|---| | `--url` | server flag | **This server's own address** — the single host Authorizer believes it is reachable at. | `https://auth.example.com` | | `--allowed-origins` | server flag | **The other apps** permitted to call this server cross-origin and be redirected to. | `https://app.example.com,https://admin.example.com` | | `authorizerURL` | SDK / client option | **The client's pointer back at the server** — what a browser or backend SDK dials. Normally the same value as `--url`. | `https://auth.example.com` | You need both flags and they are not interchangeable: `--url` is *where Authorizer is*, `--allowed-origins` is *who may talk to it*. There is no `--authorizer-url` server flag; `authorizerURL` is client-side only, and `X-Authorizer-URL` is the legacy request header `--url` replaces — ignored outright as of 2.4.0. --- ### CORS, CSRF, and origin enforcement #### CORS ```bash ./authorizer --allowed-origins=https://app.example.com,https://admin.example.com ``` - **`--allowed-origins`** (default `*`): comma-separated list of origins permitted to send credentialed cross-origin requests. A startup warning is logged when `--allowed-origins` contains `*` — this default is for development convenience and is never recommended for production. Set an explicit allowlist before deploying. #### CSRF CSRF protection is automatic and applies to every state-changing request (POST, PUT, PATCH, DELETE) other than the OAuth callback and token endpoints. Requirements: 1. **`Origin` or `Referer` header must be present.** Requests with neither are rejected with `403`. Browsers always send `Origin` on cross-origin POSTs, so this only affects scripted/curl traffic; add `-H "Origin: https://your-host"` if you hit it. 2. **The Origin must be in the allowlist.** When `--allowed-origins` contains `*`, the CSRF middleware falls back to **same-origin enforcement** — the Origin host must match the request `Host`. Wildcard CORS does not mean wildcard CSRF. 3. **One of `Content-Type: application/json` or `X-Requested-With` must be present.** Browsers cannot set these cross-origin without a successful preflight, providing a second defence layer. There is no flag to disable CSRF — if you need to bypass it for a specific automated client, use the bearer-token flow on `/oauth/token` instead of cookie-based auth. --- ### HTTP server timeouts and graceful shutdown The main HTTP server is now built with explicit timeouts to defend against slowloris and other slow-client DoS, and shuts down gracefully on SIGTERM/SIGINT (the metrics server already did this). No flags — the defaults are conservative: | Setting | Value | |---|---| | `ReadHeaderTimeout` | 10 s | | `ReadTimeout` | 30 s | | `WriteTimeout` | 60 s | | `IdleTimeout` | 120 s | | `MaxHeaderBytes` | 1 MiB | | Graceful shutdown drain | 30 s | If your deployment includes long-running uploads or streaming responses that exceed `WriteTimeout`, file an issue — we may need to make these configurable. --- ### Security response headers ```bash ./authorizer \ --enable-hsts=true \ --disable-csp=false ``` The following headers are always set: | Header | Value | |---|---| | `X-Content-Type-Options` | `nosniff` | | `X-Frame-Options` | `DENY` | | `Referrer-Policy` | `strict-origin-when-cross-origin` | | `X-XSS-Protection` | `0` | | `Permissions-Policy` | `geolocation=(), microphone=(), camera=(), payment=(), usb=()` | Token endpoint responses (`/oauth/token`) additionally set `Cache-Control: no-store, no-cache, must-revalidate, private` and `Pragma: no-cache` per [RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749) §5.1. Two opt-in flags: - **`--enable-hsts`** (default `false`): emit `Strict-Transport-Security: max-age=31536000; includeSubDomains`. Only enable when you serve over TLS — turning HSTS on without TLS will lock browsers out for a year. - **`--disable-csp`** (default `false`): disable the default `Content-Security-Policy` header. CSP is **on by default**: ``` default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self' ``` The `unsafe-inline` allowances are temporary — they will be tightened as the dashboard migrates away from inline styles. Use `--disable-csp=true` only as an escape hatch if the default policy breaks a customised dashboard in the wild. --- ### OAuth flow hardening Two fixes apply automatically; no flags. 1. **`response_mode=query` is rejected for token-bearing flows.** The `/authorize` endpoint now refuses `response_mode=query` when the `response_type` includes `token` or `id_token` (implicit and hybrid flows). Tokens in the URL query string get logged in proxy access logs and browser history — a real credential leak path. Allowed combinations: | `response_type` | `response_mode` | |---|---| | `code` | `query`, `fragment`, `form_post` | | `token`, `id_token`, hybrids | `fragment`, `form_post` | 2. **`GET /logout` is hardened against CSRF.** The endpoint still exists (OIDC RP-initiated logout requires it) but only terminates the session under one of two conditions: - The request includes a valid `id_token_hint` query parameter (an `` tag CSRF cannot synthesise a valid signed ID token), OR - The user clicks through an HTML confirmation page that issues a POST to `/logout`. Plain `GET /logout` without `id_token_hint` now serves the confirmation page instead of silently signing the user out. POST `/logout` is unchanged — first-party SDKs (`authorizer-js`, `authorizer-go`, web/app, web/dashboard) all use the GraphQL `logout` mutation and are unaffected. --- ### Webhook SSRF protection Outbound webhook calls now resolve the destination host **once** and pin the dialer to the validated IP, defeating DNS rebinding TOCTOU attacks where an attacker's DNS server returns a public IP for validation and a private IP (e.g. AWS metadata `169.254.169.254`) for the actual dial. Private, loopback, link-local, and reserved IP ranges are rejected before the dial. TLS verification still uses the original hostname via SNI, so HTTPS webhooks work normally. No flags. The protection applies to: - Admin "Test endpoint" GraphQL mutation - The webhook event dispatcher (every triggered webhook) --- ### OTP and TOTP at rest OTP and [TOTP](https://datatracker.ietf.org/doc/html/rfc6238) secrets are now protected at rest: - **OTPs (email/SMS one-time codes):** stored as HMAC-SHA256 digests keyed by `--encryption-key`. The verifier hashes the candidate and compares constant-time against the stored digest. The plaintext is only ever held in memory long enough to send the email/SMS body. - **TOTP shared secrets (authenticator app):** encrypted at rest with AES-256-GCM (using HKDF-derived keys from `--encryption-key`) and stored with an `enc:v1:` prefix. :::danger Security advisory — affected versions 2.2.1 through 2.4.0-rc.13 In those releases the at-rest key was **not** a separate input. It derived from `--jwt-secret`, and when a deployment used an asymmetric JWT algorithm (`RS*`/`ES*` with `--jwt-private-key`/`--jwt-public-key`) and set **no** `--jwt-secret`, the derivation ran over empty keying material and produced a **constant compiled into the open-source binary**. Anyone who can read the repository can compute it. **If you ran an affected version with `RS*`/`ES*` and no `--jwt-secret`,** a copy of your database yields recoverable TOTP seeds and every outstanding OTP digest — including password-reset codes, whose 10⁶ search space is trivial once the key is known. Remediation, in order: 1. Set `--encryption-key` to a fresh random value (`openssl rand -hex 32`). 2. Force TOTP re-enrolment for all users — existing ciphertext was written under the old key and **cannot** be decrypted with the new one. There is no re-encryption path. 3. Invalidate outstanding password-reset and verification OTPs. From 2.4.0 the key is its own input and an `RS*`/`ES*` deployment without one **refuses to start** rather than falling back silently. ::: #### Migration There is **no flag** for OTP/TOTP migration. The handlers transparently handle both forms: - **OTPs:** in-flight legacy plaintext rows expire within minutes naturally. New writes are always hashed. - **TOTP:** the read path tries decryption first, falls back to treating the stored value as a legacy base32 secret if it doesn't have the `enc:v1:` prefix. On a successful legacy validation, the row is re-encrypted in place (best-effort — a write failure does not fail the login). #### Rolling-deploy note for multi-replica clusters If you run **multiple Authorizer replicas** behind a load balancer and roll out this release across them one at a time, there is a window during which a TOTP user's row may be migrated to `enc:v1:` by a new replica and then read by an old replica that doesn't understand the prefix. The user-visible impact is bounded — TOTP codes regenerate every 30 s — but it's real. Mitigations, in order of preference: 1. **Atomic deploy.** Replace all replicas at once (drain → replace). This is the typical Authorizer deployment model and avoids the issue entirely. 2. **Brief maintenance window.** Disable TOTP login at the load balancer for the duration of the rollout. 3. **Accept the window.** TOTP users may need to retry their code once during the rollout. For **single-binary deployments** (one Authorizer process on one host) this is a non-issue — there are no other replicas to disagree with. #### Key rotation Both OTP and TOTP at-rest protection are keyed by `--encryption-key`. Rotating it will lock out every user with an enrolled TOTP authenticator until they re-enrol, because the existing ciphertext can no longer be decrypted. If you must rotate, plan a TOTP re-enrolment campaign (or a temporary fallback path) before doing so. `--encryption-key` falls back to `--jwt-secret` when it is not set, which keeps HMAC (`HS*`) deployments working unchanged — but it means rotating `--jwt-secret` on such a deployment silently rotates the at-rest key too. Set `--encryption-key` explicitly to decouple the two; the server warns at startup when both are set to the same value. The server logs an explicit error on every TOTP validation that fails to decrypt: ``` failed to decrypt stored TOTP secret; check that --encryption-key (or --jwt-secret, if no encryption key is set) has not changed since enrollment ``` --- ### Multi-factor authentication (MFA) & Passkeys MFA methods — TOTP, email OTP, SMS OTP, and [WebAuthn](https://www.w3.org/TR/webauthn-2/)/passkey as a second factor — are **enabled by default**. `--enforce-mfa` defaults to `false`: MFA is optional and skippable unless you turn enforcement on. See [Server Configuration](./server-config#multi-factor-authentication-mfa--webauthnpasskeys) for the full flag reference (`--enforce-mfa`, `--disable-mfa`, `--disable-totp-login`, `--disable-webauthn-mfa`, `--disable-email-otp`, `--disable-sms-otp`). #### Per-method availability The public `meta` GraphQL query exposes whether each method is actually usable right now (config flag **and**, for email/SMS OTP, provider configured): | Field | True when | |---|---| | `is_totp_mfa_enabled` | MFA enabled and `--disable-totp-login` is not set | | `is_email_otp_mfa_enabled` | MFA enabled, `--disable-email-otp` is not set, and SMTP is configured | | `is_sms_otp_mfa_enabled` | MFA enabled, `--disable-sms-otp` is not set, and [Twilio](https://www.twilio.com) is configured | | `is_webauthn_enabled` | MFA enabled and `--disable-webauthn-mfa` is not set — this reflects WebAuthn's availability **as an MFA factor only**; primary passkey login/registration has no flag and is always available regardless of this field | | `is_mfa_enforced` | mirrors `--enforce-mfa` | `_admin_meta.is_multi_factor_auth_service_enabled` reports whether MFA can be used at all on this instance (at least one usable method) — the dashboard uses it to gate the per-user "require MFA" toggle. #### Withheld-token first-time setup Login/signup/OAuth-callback resolve a per-user MFA "gate" before issuing a token: | Gate | Trigger | Token behavior | |---|---|---| | none | MFA doesn't apply to this user and isn't enforced | issued normally | | block-verify | user already has a verified factor (TOTP, passkey, email-OTP, or SMS-OTP) | **withheld** until they verify it — never skippable | | block-enroll | `--enforce-mfa` is set and the user hasn't enrolled anything yet | **withheld** until enrollment completes — never skippable | | offer-all | MFA is available but not enforced, user hasn't enrolled, and has never skipped before | **withheld** until the user completes a method or calls `skip_mfa_setup` | | skipped | same as offer-all, but the user already chose Skip once | issued normally, no nag | In every withheld case the response carries no `access_token` — only a message and a set of `should_show_*` / `should_offer_*` flags on `AuthResponse` (`should_show_totp_screen`, `should_offer_webauthn_mfa_setup`, `should_offer_email_otp_mfa_setup`, `should_offer_sms_otp_mfa_setup`, `should_offer_webauthn_mfa_verify`). The follow-up call (`verify_otp`, `totp_mfa_setup`, `webauthn_registration_verify`, `webauthn_login_verify`, or `skip_mfa_setup`) is authenticated by a short-lived **MFA session** set alongside that response, not by a bearer token — none has been issued yet. `should_offer_mfa_setup` is deprecated and never set; ignore it. ##### Completing the flow from a non-browser client The MFA session travels as a cookie, but it is **not browser-only**. It is an ordinary `Set-Cookie` response header carrying an opaque handle, and the server accepts it back in an ordinary `Cookie` request header — so any HTTP client can complete the flow. A browser does it automatically; everything else reads one value and sends it back. ```bash # 1. Sign up. The token is withheld; the handle arrives in Set-Cookie. curl -i -X POST "$AUTHORIZER_URL/graphql" \ -H 'Content-Type: application/json' -H "Origin: $AUTHORIZER_URL" \ -d '{"query":"mutation { signup(params: {email: \"a@b.com\", password: \"Password@123\", confirm_password: \"Password@123\"}) { access_token message } }"}' # HTTP/1.1 200 OK # Set-Cookie: mfa_session=e415fa93-f51e-4ee1-8568-bd7cf2e0fa67; ... # {"data":{"signup":{"access_token":null,"message":"Proceed to mfa setup"}}} # 2. Echo it back. No cookie jar involved. curl -X POST "$AUTHORIZER_URL/graphql" \ -H 'Content-Type: application/json' -H "Origin: $AUTHORIZER_URL" \ -H 'Cookie: mfa_session=e415fa93-f51e-4ee1-8568-bd7cf2e0fa67' \ -d '{"query":"mutation { skip_mfa_setup(params: {email: \"a@b.com\"}) { access_token } }"}' # -> access_token issued ``` Over **gRPC** the same handle is carried as metadata: read it from the `set-cookie` response metadata, send it back as a `cookie` entry. :::caution Send it only to your own Authorizer A browser's cookie jar scopes cookies to the origin that set them. If you carry the handle by hand you take on that job: **attach it only to requests to your configured Authorizer base URL, and never follow a redirect while it is attached.** The handle authenticates a half-completed login — `skip_mfa_setup` exchanges it for a full access token — so treat it exactly like a credential: hold it in memory for the duration of the flow, never log it, never persist it. ::: You do not need a general-purpose cookie jar for this, and reaching for one has been a reliable source of bugs: `Secure` cookies are dropped over `http://localhost` by some HTTP stacks, and domain-matching rules vary between languages. Reading `mfa_session` by name and echoing it back to one known origin has none of those failure modes. The official [Go](https://github.com/authorizerdev/authorizer-go) and [Python](https://github.com/authorizerdev/authorizer-py) SDKs do this for you. A registered passkey satisfies MFA on its own — no OTP/TOTP re-challenge — because every WebAuthn assertion already requires user verification (biometric/PIN) at the authenticator. #### Lockout & admin recovery Two independent lockout mechanisms exist: 1. **Transient per-user rate limit.** `verify_otp` (TOTP, TOTP recovery code, email OTP, and SMS OTP all share this) allows **5 failed attempts per user in a 15-minute sliding window**; the 6th failing attempt returns `429 Too Many Requests` for the rest of that window. This is on top of the global per-IP rate limiter and closes the gap where one account is brute-forced from many IPs. A storage-layer fault to the counter fails open (never locks a legitimate user out because of an infra blip). 2. **Permanent, self-declared lockout.** The `lock_mfa` mutation lets a user who has lost access to their only MFA factor (with no working OTP fallback) mark their own account locked (`mfa_locked_at`). It's refused if the user has a verified email/SMS OTP fallback available — use that instead. Once locked, **all** login attempts for that user (password, passkey, everything) are rejected until an admin clears it. Admin recovery is the `_update_user` mutation with `reset_mfa: true`. It clears `mfa_locked_at`, the user's `is_multi_factor_auth_enabled` override, and `has_skipped_mfa_setup_at`, and **deletes every enrolled authenticator (TOTP/email-OTP/SMS-OTP) and every registered WebAuthn credential** for that user — their next login lands back on the same first-time MFA setup screen a brand-new account sees. ```graphql mutation { _update_user(params: { id: "user-id", reset_mfa: true }) { id mfa_locked_at enrolled_mfa_methods } } ``` `User.mfa_locked_at` and `User.enrolled_mfa_methods` (any of `"totp"`, `"webauthn"`, `"email_otp"`, `"sms_otp"`) let an admin dashboard show which users are locked and what they have enrolled without guessing from `is_multi_factor_auth_enabled` alone. #### Recovery codes TOTP enrollment (`totp_mfa_setup`, or the enrollment payload returned inline by a `block-enroll`/`offer-all` login response) issues **10 single-use recovery codes**, shown to the user exactly once. At rest they are stored as **SHA-256 hashes** (not the plaintext codes) and each is marked consumed the first time it validates successfully — a stolen database dump never yields usable codes, and a code can't be replayed. #### WebAuthn / passkey ceremonies WebAuthn/passkey support is `web/app` (end-user login) only — **`web/dashboard` admin login is untouched** (`_admin_login` has no passkey path). The self-service GraphQL operations (no `_` admin prefix): | Operation | Purpose | |---|---| | `webauthn_registration_options(email, phone_number)` | begin registering a new passkey; returns JSON `PublicKeyCredentialCreationOptions` for `navigator.credentials.create()` | | `webauthn_registration_verify(params: { name, credential, email, phone_number, state })` | verify the attestation and persist the credential | | `webauthn_login_options(email: String)` | begin a login ceremony — omit `email` for **usernameless/discoverable** login (any resident passkey for the origin); pass it for the **MFA-alternative** flow, scoped to that user's own credentials | | `webauthn_login_verify(params: { credential, state })` | verify the assertion and issue tokens through the same path as `login`/`verify_otp` | | `webauthn_credentials` (query) | list the caller's own registered passkeys | | `webauthn_delete_credential(id)` | delete one of the caller's own passkeys | `options`/`credential` are opaque JSON strings carrying the WebAuthn `PublicKeyCredential*` structures; the SDK handles the base64url ⟷ `ArrayBuffer` conversion between these and the browser's `navigator.credentials` API. ```graphql mutation BeginPasskeyLogin { webauthn_login_options { options } } mutation FinishPasskeyLogin($credential: String!) { webauthn_login_verify(params: { credential: $credential }) { access_token id_token refresh_token message } } ``` Both registration operations also accept an MFA-session-cookie caller (no bearer token yet) during a token-withheld `offer-all`/`block-enroll` login — completing registration there resolves the gate and issues the previously withheld token, the same way `totp_mfa_setup` + `verify_otp(is_totp: true)` does for TOTP. **Email-verification gate:** `webauthn_login_verify` is stricter than password login — it refuses to issue tokens until the account's email is verified, returning a distinct, actionable error (`email is not verified. please verify your email before signing in with a passkey`) rather than a generic invalid-credential error. This matters most for passkey-only signup (no password at all): the first login attempt with that passkey is refused until the user verifies their email through the normal verification-email flow. A locked-out account (`mfa_locked_at` set) is refused at `webauthn_login_verify` too, with the same message as password/OTP login. --- ### GraphQL hardening ```bash ./authorizer \ --graphql-max-complexity=300 \ --graphql-max-depth=15 \ --graphql-max-aliases=30 \ --graphql-max-body-bytes=1048576 ``` The GraphQL endpoint now enforces four limits, all configurable: - **`--graphql-max-complexity`** (default `300`): caps the total complexity score of a single operation. Defends against expensive resolver chains. - **`--graphql-max-depth`** (default `15`): caps the nesting depth of a selection set. Defends against deeply nested DoS queries. - **`--graphql-max-aliases`** (default `30`): caps the total number of aliased fields per operation. Defends against alias-amplification attacks where a client fans out the same expensive field many times under different aliases without changing the complexity score. - **`--graphql-max-body-bytes`** (default `1048576`, 1 MiB): caps the request body size. Defends against oversized-payload DoS. Two side effects: - **GET on `/graphql` is no longer accepted.** Queries (and especially mutations) over GET leak into proxy logs, server access logs, and browser history. Clients must POST. All first-party SDKs already POST. - **A new Prometheus counter** records rejections by limit kind: ``` authorizer_graphql_limit_rejections_total{limit="depth"|"complexity"|"alias"|"body_size"} ``` See [Metrics & Monitoring](./metrics-monitoring) for details. Alert on a sustained non-zero rate to spot abuse, or to detect that a limit is too tight for your legitimate operation surface. --- ### Rate limiter behaviour changes Two correctness fixes that may change observed behaviour: 1. **Redis backend errors now propagate.** Previously, a Redis error in the rate-limit check was silently swallowed and the request was allowed through, regardless of `--rate-limit-fail-closed`. The flag now actually takes effect: when `--rate-limit-fail-closed=true`, a failing Redis returns `503` to the caller; otherwise the request is allowed and the error is logged. 2. **The Redis sliding window length is now `ceil(burst / rps)` seconds** instead of integer-division-truncated. With `burst < rps` the previous math produced a 0-second window and effectively disabled the limit. The in-memory backend was already correct; this aligns Redis with it. --- ### Login error normalization All login failures now return the same generic `invalid credentials` error message regardless of the underlying reason (user not found, wrong password, email not verified, wrong auth method, account revoked). The specific reason is recorded in the debug log for ops visibility but never returned to the client. A precomputed dummy bcrypt comparison runs on the user-not-found and other early-exit paths so request latency matches the real password verification path. Without this, an attacker can distinguish "no such user" from "wrong password" by measuring response time. `forgot_password`, `resend_verify_email`, and `magic_link_login` follow the same pattern: they return the **same** generic success message whether or not the email matches an existing account, with a hint to double-check for typos: > *If an account exists for this email, a [reset link / verification > link / magic link] has been sent. Please check your inbox. If you > don't receive it within a few minutes, double-check the email address > for typos.* This kills the user-enumeration attack surface entirely. --- ### Fine-grained authorization Authorizer ships an embedded **[OpenFGA](https://openfga.dev)** (ReBAC) engine, and access checks **fail closed** — a `check_permissions` for a relation that the relationship tuples don't grant is denied, and any engine or store error denies rather than allows. There is no permissive "log but allow" mode. See [Authorization (FGA)](./authorization) for the authorization model, admin mutations, and per-endpoint usage. --- ### See also - [Server Configuration](./server-config) — full CLI flag reference - [Authorization (FGA)](./authorization) — OpenFGA authorization model, tuples, and access checks - [Rate Limiting](./rate-limiting) — rate limiter configuration - [Metrics & Monitoring](./metrics-monitoring) — Prometheus metrics including the new GraphQL limit counter - [v1 to v2 Migration](../migration/v1-to-v2) — for users upgrading from v1 --- ## Server Configuration ## Server Configuration (v2) Authorizer v2 uses **CLI flags only** for configuration. Nothing is loaded from `.env` files or dashboard-managed env, and config is not persisted in the database or cache. If you are migrating from v1, first skim the high-level [Migration v1 to v2](../migration/v1-to-v2) guide and then use this page as a reference. --- ### 1. Core flags ```bash ./authorizer \ --env=production \ --http-port=8080 \ --host=0.0.0.0 \ --metrics-port=8081 \ --metrics-host=127.0.0.1 \ --log-level=info ``` - **`--env`**: environment name (for example `production`, `development`). - **`--http-port`**: HTTP listen port (default `8080`). - **`--host`**: bind address for the **main** HTTP server (default `0.0.0.0`). - **`--metrics-port`**: port for the dedicated **`/metrics`** listener (default `8081`; **must differ** from `--http-port`). Health probes stay on the HTTP port. - **`--metrics-host`**: bind address for that **dedicated** metrics listener only (default `127.0.0.1`). The main app can listen on all interfaces while metrics stay on loopback. For Docker/Kubernetes scraping from another container/pod, set **`--metrics-host=0.0.0.0`** and keep the metrics port on an internal network only (never on a public load balancer). - **`--log-level`**: one of `debug`, `info`, `warn`, `error`, `fatal`, `panic`. --- ### 2. Database and session store #### Database ```bash ./authorizer \ --database-type=postgres \ --database-url="postgres://user:pass@host/db" \ --database-name=authorizer \ --database-host=db-host \ --database-port=5432 ``` Key flags: - **`--database-type`**: `postgres`, `yugabyte`, `cockroachdb`, `serenedb`, `surrealdb`, `mysql`, `mariadb`, `planetscale`, `sqlite`, `libsql`, `sqlserver`, `mongodb`, `arangodb`, `cassandradb`, `scylladb`, `couchbase`, `dynamodb` - **`--database-url`**: connection string. - **`--surrealdb-namespace`**: SurrealDB namespace that holds `--database-name` (default `authorizer`). SurrealDB only. - Optional per-driver flags (name, host, port, TLS certs, etc.) -- see the mapping table in [Migration v1 to v2](../migration/v1-to-v2#database). #### Session / cache ```bash ./authorizer \ --redis-url=redis://user:pass@redis-host:6379/0 ``` - **`--redis-url`**: Redis connection string used for session storage. If omitted, sessions are stored in memory (suitable only for dev / single-node setups). --- ### 3. OAuth / app behavior These flags replace v1 env such as `CLIENT_ID`, `CLIENT_SECRET`, and app behavior toggles. ```bash ./authorizer \ --client-id=YOUR_CLIENT_ID \ --client-secret=YOUR_CLIENT_SECRET \ --admin-secret=your-admin-secret \ --allowed-origins=https://your-app.com,http://localhost:3000 \ --default-authorize-response-type=code \ --default-authorize-response-mode=query ``` - **`--client-id`** (required): instance/client identifier. - **`--client-secret`** (required): secret used for token-related operations. - **`--admin-secret`** (**required, non-empty**): super-admin secret for admin operations. **Breaking change as of April 2026**: there is no default any more — empty causes the server to exit at startup. Pick any non-empty value; the strength of the secret is your responsibility. See [Security Hardening](./security#admin-authentication). - **`--allowed-origins`**: comma-separated list of allowed origins (default `*`). A startup warning is logged when the value contains `*` — set an explicit allowlist for production. See [CORS, CSRF and origin enforcement](./security#cors-csrf-and-origin-enforcement). - **`--redirect-uris`** (default empty, new in 2.4.0): comma-separated list of **exact** redirect URIs for this deployment's own client — the one named by `--client-id`. When set, `redirect_uri` on `/authorize` is matched exactly against this list, which is what [OIDC Core §3.1.2.1](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest) and [RFC 6749 §3.1.2.3](https://www.rfc-editor.org/rfc/rfc6749#section-3.1.2.3) require. When empty, matching falls back to `--allowed-origins`, which compares **origins** — so `https://app.example.com/anything` is accepted for a deployment that only meant `https://app.example.com/callback`. :::warning It applies to every flow carrying this `client_id` This is not a per-app setting. List **every** redirect URI your apps use — each app's callback, and any local development callback — or those logins start being refused with `invalid redirect_uri`. Entries that could never match (no scheme, a fragment, embedded user info) are rejected at startup rather than at login time. ::: Loopback redirects keep the [RFC 8252 §7.3](https://datatracker.ietf.org/doc/html/rfc8252#section-7.3) carve-out: a registered `http://127.0.0.1/callback` matches any port, because a native app binds an ephemeral one. Scheme, host, path and query must still match exactly. - **`--trusted-proxies`** (default empty): comma-separated CIDRs of reverse proxies whose `X-Forwarded-For` should be honoured. **Breaking change as of April 2026**: defaults to none — operators behind a proxy must set this explicitly or rate limiting and audit logs will key on the proxy IP. See [Trusted proxies](./security#trusted-proxies). - **`--url`** (**required** as of 2.4.0): this server's own canonical base URL (e.g. `https://auth.example.com`). It is the only source used to build verification/reset/magic-link email URLs, the JWT `iss` claim, and OIDC discovery URLs; the `X-Authorizer-URL`, `X-Forwarded-Host` and `Host` request headers are ignored for that purpose. The server refuses to start if it is missing or malformed. **This is not `--allowed-origins`** — that lists the *apps* allowed to talk to this server, while `--url` is *where this server is*; you need both. See [Trusted base URL](./security#trusted-base-url) for the rationale and a comparison with the SDKs' `authorizerURL` option. Organization / UI: ```bash ./authorizer \ --organization-name="Your Company" \ --organization-logo="https://your-cdn/logo.png" \ --enable-login-page=true \ --enable-playground=false \ --enable-graphql-introspection=false ``` - **`--enable-login-page`**: set to `false` to disable the built-in login UI. - **`--enable-playground`**: set to `false` to disable the GraphQL playground. - **`--enable-graphql-introspection`**: set to `false` in hardened environments. - **`--enable-ciba`** (beta, 2.5.0+): human approval for agent actions (OpenID CIBA, poll mode). See [Human Approval for Agent Actions](../enterprise/ciba) for this flag and the `--ciba-*` flags. --- ### 4. Auth behavior and cookies #### Roles and auth flows ```bash ./authorizer \ --roles=user,admin \ --default-roles=user \ --protected-roles=admin \ --enable-strong-password=true \ --enable-basic-authentication=true \ --enable-email-verification=true \ --enable-magic-link-login=true \ --enable-signup=true ``` These replace v1 flags such as `DISABLE_BASIC_AUTHENTICATION`, `DISABLE_EMAIL_VERIFICATION`, etc. See the [Auth behavior mapping](../migration/v1-to-v2#auth-behavior) for exact correspondences. :::danger Breaking in 2.4.0 — `--enable-email-verification` requires SMTP Starting the server with `--enable-email-verification=true` and no working mail path is now a **fatal boot error**. It used to start and fail silently per user. Every route back into an unverified account terminates at the same mailbox, so without SMTP a user is created unverified and can never recover — and an unverified account also blocks a federated login for the same address. That is unrecoverable state, so it fails where an operator can see it rather than one user at a time. A "working mail path" means all three of `--smtp-host`, `--smtp-port` (greater than zero) and `--smtp-sender-email`. Setting only the host still fails. Either configure SMTP or set `--enable-email-verification=false`. ::: #### Multi-factor authentication (MFA) & WebAuthn/passkeys **Breaking change**: `--enable-mfa`, `--enable-totp-login`, `--enable-email-otp`, and `--enable-sms-otp` are **removed**. [TOTP](https://datatracker.ietf.org/doc/html/rfc6238), email OTP, SMS OTP, and [WebAuthn](https://www.w3.org/TR/webauthn-2/)/passkey-as-MFA are now all **on by default**; opt out per method with the `--disable-*` flags below. `--enforce-mfa` also flipped its default from `true` to `false` — MFA is now optional and skippable unless you explicitly enforce it. ```bash ./authorizer \ --enforce-mfa=false \ --disable-mfa=false \ --disable-totp-login=false \ --disable-webauthn-mfa=false \ --disable-email-otp=false \ --disable-sms-otp=false ``` - **`--enforce-mfa`** (default `false`): require every user to complete MFA enrollment before a token is issued (`mfaGateBlockEnroll`, never skippable). When `false`, users are offered MFA setup once and may skip it (`skip_mfa_setup` mutation); a user's own already-enrolled factor is always required to verify regardless of this flag. - **`--disable-mfa`** (default `false`): one-way global kill switch — forces MFA off entirely (TOTP/email-OTP/SMS-OTP unavailable, `--enforce-mfa` neutralized) regardless of the per-method flags below. Does **not** affect WebAuthn/passkey as a **primary login method** (only as an MFA factor). - **`--disable-totp-login`** (default `false`): disable TOTP authenticator-app MFA. - **`--disable-webauthn-mfa`** (default `false`): disable WebAuthn/passkey as an **MFA factor**. Does not affect WebAuthn/passkey as a primary, passwordless login method — that is always available and has no flag. - **`--disable-email-otp`** (default `false`): disable email-OTP MFA. Only takes effect when SMTP is configured (`--smtp-*`); otherwise email OTP is unavailable regardless of this flag. - **`--disable-sms-otp`** (default `false`): disable SMS-OTP MFA. Only takes effect when [Twilio](https://www.twilio.com) is configured (`--twilio-*`); otherwise SMS OTP is unavailable regardless of this flag. Effective availability of each method is exposed on the public `meta` GraphQL query (`is_totp_mfa_enabled`, `is_email_otp_mfa_enabled`, `is_sms_otp_mfa_enabled`, `is_webauthn_enabled`, `is_mfa_enforced`) so frontends never have to reverse-engineer flag combinations. See [MFA & Passkeys](./security#multi-factor-authentication-mfa--passkeys) for the full behavior — withheld-token first-time setup, lockout, admin recovery, and the WebAuthn/passkey GraphQL operations. #### Cookies ```bash ./authorizer \ --app-cookie-secure=true \ --admin-cookie-secure=true \ --app-cookie-same-site=none ``` - **`--app-cookie-secure`** / **`--admin-cookie-secure`** (both default `true`): use `true` for HTTPS-only cookies in production. - **`--app-cookie-same-site`** (default `none`): `SameSite` attribute for the session cookies — one of `lax`, `strict`, or `none`. The default of `none` is what allows an app on a **different site** to complete a credentialed `/session` call at all. Set `lax` only when every app that reads the session shares this host; it is the tighter setting, but it stops cross-site session reads working. :::caution The value is validated at boot (2.4.0) An unrecognised value now **exits at startup** instead of silently falling back to `lax`. That fallback was the dangerous part: an operator who asked for `strict` and mistyped it got `lax` — a real downgrade from what they requested, with nothing anywhere saying so. A mistyped `none` went the other way and withheld the session cookie from cross-site apps, which presents as "login randomly doesn't stick" with the cause three layers away. ::: `strict` is accepted, but note that one cookie deliberately ignores this setting: the short-lived OAuth `state` cookie used during social login is always `Lax`, or `None` when secure. A provider's callback arrives as a cross-site redirect — a cross-site `form_post` for Apple — and `Strict` withholds cookies on exactly those, so honouring `strict` there would break every social login on the deployment. --- ### 5. JWT configuration ```bash ./authorizer \ --jwt-type=HS256 \ --jwt-secret=your-jwt-secret \ --jwt-role-claim=role ``` Or for asymmetric keys: ```bash ./authorizer \ --jwt-type=RS256 \ --jwt-private-key="$(cat /path/to/private.key)" \ --jwt-public-key="$(cat /path/to/public.key)" \ --encryption-key=your-encryption-key ``` Additional flags: - **`--custom-access-token-script`**: path/string for custom token augmentation logic (advanced use only). - **`--refresh-token-expires-in`** (default `2592000`, 30 days): refresh-token lifetime in seconds. Previously hardcoded — now operator-configurable. - **`--encryption-key`** (no default): the key used to encrypt secrets **at rest** — TOTP shared secrets and OTP digests. Separate from the JWT signing material. In v2, the `_generate_jwt_keys` mutation is deprecated and returns an error; configure keys **only via flags**. :::warning Breaking change in 2.4.0 — `--encryption-key` At-rest encryption no longer derives from `--jwt-secret`. **A deployment using an asymmetric JWT algorithm (`RS*`/`ES*`) with no `--jwt-secret` will refuse to start until `--encryption-key` is set.** HMAC deployments (`HS256`/`HS384`/`HS512`) are unaffected: the key still falls back to `--jwt-secret`, so no change is required. This closes a vulnerability in **2.2.1 through 2.4.0-rc.13** where that fallback produced a publicly known constant for asymmetric deployments — read the [security advisory](./security#otp-and-totp-at-rest) before upgrading, as remediation includes forcing TOTP re-enrolment. ::: > **Note on key rotation:** `--encryption-key` protects TOTP shared secrets at > rest and HMACs OTPs. Rotating it will lock out every user with an enrolled > TOTP authenticator until they re-enrol. When it is unset it falls back to > `--jwt-secret`, so on those deployments rotating the JWT secret rotates the > at-rest key too. See > [OTP and TOTP at rest](./security#otp-and-totp-at-rest). --- ### 6. SMTP and SMS #### SMTP ```bash ./authorizer \ --smtp-host=smtp.mailprovider.com \ --smtp-port=587 \ --smtp-username=user@example.com \ --smtp-password=strong-password \ --smtp-sender-email=auth@example.com \ --smtp-sender-name="Auth Team" \ --smtp-local-name=authorizer \ --smtp-skip-tls-verification=false ``` #### Twilio (SMS OTP) ```bash ./authorizer \ --twilio-account-sid=AC... \ --twilio-api-key=... \ --twilio-api-secret=... \ --twilio-sender=+123456789 ``` --- ### 7. Social / OAuth providers Each provider uses its own set of flags: ```bash ./authorizer \ --google-client-id=... \ --google-client-secret=... \ --google-scopes="openid,email,profile" \ --github-client-id=... \ --github-client-secret=... \ --github-scopes="read:user,user:email" ``` Other supported providers follow the same pattern: - `--facebook-client-id`, `--facebook-client-secret`, `--facebook-scopes` - `--microsoft-client-id`, `--microsoft-client-secret`, `--microsoft-tenant-id`, `--microsoft-allowed-tenants`, `--microsoft-scopes` - `--apple-client-id`, `--apple-client-secret`, `--apple-scopes` - `--linkedin-client-id`, `--linkedin-client-secret`, `--linkedin-scopes` - `--discord-client-id`, `--discord-client-secret`, `--discord-scopes` - `--twitter-client-id`, `--twitter-client-secret`, `--twitter-scopes` - `--twitch-client-id`, `--twitch-client-secret`, `--twitch-scopes` - `--roblox-client-id`, `--roblox-client-secret`, `--roblox-scopes` #### Provider email attestation (2.4.0) :::warning Breaking in 2.4.0 A social login whose provider does **not** attest the email address no longer signs the user into an existing account with that address. OAuth proves the user holds an account at the provider. It proves nothing about the email address that provider hands back — which is why OIDC has a separate `email_verified` claim. Microsoft Entra is the practical case: on a multi-tenant alias the `email` claim is **mutable and unattested**, so anyone able to set a directory attribute in *their own* tenant could assert your address and be logged into your account. This is the [nOAuth](https://www.descope.com/blog/post/noauth) class of account takeover. Signup with an unattested address still works — it just creates its own account instead of reaching an existing one. ::: Attestation comes from the provider's `email_verified` claim, or Entra's `xms_edov` optional claim. To make Entra attest: - pin `--microsoft-tenant-id` to a single tenant, **or** - enable the `xms_edov` optional claim on the app registration, **or** - list the tenants you trust in `--microsoft-allowed-tenants` when `--microsoft-tenant-id` is a multi-tenant alias (`common`, `organizations`, `consumers`). Empty means no restriction — and in that mode the tenant is untrusted, so the email it asserts will not link to an existing account. `--oauth-allow-unverified-provider-email=true` is a temporary compatibility escape hatch. It does **not** disable the check: an unattested address still cannot cross into an account owned by another credential. It only re-permits same-provider linking, which leaves two Entra tenants able to collide on one address. The server logs a warning on every boot while it is set. See [Email verification contract](./email-verification-contract) for the per-provider signal table and the upgrade path. --- ### 8. Rate limiting ```bash ./authorizer \ --rate-limit-rps=30 \ --rate-limit-burst=20 \ --rate-limit-fail-closed=false ``` - **`--rate-limit-rps`**: maximum sustained requests per second per IP (default `30`). Set to `0` to disable. - **`--rate-limit-burst`**: maximum burst size per IP (default `20`). - **`--rate-limit-fail-closed`**: when `true`, a failing rate-limit backend returns `503` instead of allowing the request (default `false`, fail-open). Rate limiting is always enabled by default. When `--redis-url` is set, limits are shared across replicas via Redis. See [Rate Limiting](./rate-limiting) for full details. --- ### 9. Admin and GraphQL security flags New in v2: ```bash ./authorizer \ --disable-admin-header-auth=true \ --enable-graphql-introspection=false \ --graphql-max-complexity=300 \ --graphql-max-depth=15 \ --graphql-max-aliases=30 \ --graphql-max-body-bytes=1048576 ``` - **`--disable-admin-header-auth`**: when `true`, the server ignores `X-Authorizer-Admin-Secret` and only honors the secure admin cookie. **Recommended for production.** - **`--enable-graphql-introspection`**: disable in locked-down environments. - **`--graphql-max-complexity`** (default `300`): max total complexity score per operation. - **`--graphql-max-depth`** (default `15`): max selection-set nesting depth. - **`--graphql-max-aliases`** (default `30`): max aliased fields per operation (defends against alias amplification). - **`--graphql-max-body-bytes`** (default `1048576`, 1 MiB): max GraphQL request body size. `GET /graphql` is no longer accepted — clients must POST. Rejections are counted in the `authorizer_graphql_limit_rejections_total` [Prometheus](https://prometheus.io) metric, labelled by limit kind. See [GraphQL hardening](./security#graphql-hardening) for details. #### Authorization (FGA) ```bash ./authorizer \ --fga-store=postgres \ --fga-store-url="postgres://user:pass@host/db" ``` - **`--fga-store`**: backing store for the embedded [OpenFGA](https://openfga.dev) engine — one of `sqlite`, `postgres`, `mysql`, or `memory`. Only needed when the main database is NoSQL (see paragraph below); for SQL main databases the engine reuses that database automatically. - **`--fga-store-url`**: connection string for the FGA store when `--fga-store` is set to a database driver. - **`--fga-allow-unconstrained-agents`** (default `false`): see below. ##### `--fga-allow-unconstrained-agents` :::warning Escape hatch — changes an authorization outcome A delegated (agent-acting-for-user) permission check evaluates `perms(agent) ∩ perms(user)`. If the authorization model declares no `type agent`, the agent half **cannot be evaluated at all**. As of 2.4.0 that check is **denied**. Previously it authorized as the delegating user alone, which silently handed the agent the user's full authority — the Confused Deputy the intersection exists to prevent. A security check that cannot be evaluated is not a check that passes. Setting this flag to `true` restores the pre-2.4.0 behaviour while you migrate a model. It does not make anything more permissive than 2.3.x was, but it does mean **agents carry their delegating user's full authority**. Every such request is logged at warn level and recorded as `not_enforced` on the delegated-check metric, so the exposure shows up in dashboards rather than being discovered during an incident. The fix is to add `type agent` to your model — see [Agent identity](../enterprise/agent-identity). Grant your agents *before* deploying the model, or their calls start being denied. ::: Authorizer ships an embedded **OpenFGA** (ReBAC) engine. It is enabled by default when the main database is SQL-compatible (SQLite/Postgres/MySQL) and reuses that database. For NoSQL main databases (MongoDB, DynamoDB, …) it is off unless you set `--fga-store` (one of `sqlite`/`postgres`/`mysql`/`memory`) and `--fga-store-url`. Checks fail closed. See [Authorization (FGA)](./authorization). --- ### 9. Security headers ```bash ./authorizer \ --enable-hsts=true \ --disable-csp=false ``` - **`--enable-hsts`** (default `false`): emit `Strict-Transport-Security`. Only enable behind TLS — turning HSTS on without TLS will lock browsers out for a year. - **`--disable-csp`** (default `false`): disable the default `Content-Security-Policy` header. CSP is on by default. The defaults are conservative and documented at [Security response headers](./security#security-response-headers). --- ### 10. Full security reference See the dedicated [Security Hardening](./security) page for: - The complete list of security CLI flags introduced in April 2026 - Trusted-proxy configuration for various deployment topologies - CSRF, CORS, OAuth flow, and webhook SSRF protections (all automatic) - OTP and TOTP at-rest hardening, including the rolling-deploy note for multi-replica clusters - Login error normalization and user-enumeration defences - Multi-factor authentication (MFA) behavior, lockout, admin recovery, and WebAuthn/passkey ceremonies --- ### 11. Discovering all flags To list all available flags and their defaults, run: ```bash ./authorizer --help ``` For a v1 to v2 mapping table, see [Configuration Mapping](../migration/v1-to-v2#3-configuration-mapping-v1-env--v1-behavior-to-v2-cli-flags). --- ## SSO — One-Stop Authentication for All Your Apps Authorizer can serve as the **central Single Sign-On (SSO) Identity Provider** for every application in your organization. Instead of each app managing its own user accounts and login flows, all apps delegate authentication to one Authorizer instance. Users sign in once and get seamless access everywhere. ### Architecture Overview ```mermaid flowchart TB D["Internal Dashboard
(React)"] P["Customer Portal
(Next.js)"] T["Admin Tools
(Go CLI)"] E["Third-Party
(Grafana, GitLab, ...)"] D & P & T & E -- "OIDC Authorization Code + PKCE" --> Auth subgraph Auth["AUTHORIZER (Central IdP)"] F["Unified user store · Session management
MFA / TOTP · RBAC · Social logins · Custom token claims"] end Auth -- "optional upstream federation" --> Google & GitHub & Azure & Apple & Facebook ``` Every app talks to Authorizer using standard **OIDC Discovery**. Point your app at `https://auth.yourcompany.com/.well-known/openid-configuration` and the client library auto-discovers all endpoints. --- ### Why Use Authorizer as Your SSO | Benefit | Details | |---------|---------| | **Single user store** | One account per person across all apps. No duplicate credentials, no sync headaches. | | **One login, all apps** | Session cookie means users authenticate once. Subsequent apps get silent SSO via `prompt=none`. | | **Centralized MFA** | [TOTP](https://datatracker.ietf.org/doc/html/rfc6238), email OTP, or SMS OTP configured once per user, enforced everywhere. | | **Unified roles** | Assign roles centrally; each app reads the `roles` claim from the JWT and enforces its own authorization. | | **Self-hosted & sovereign** | Your infrastructure, your data. No third-party vendor sees your user credentials. | | **Standards-based** | Full OIDC Core 1.0, OAuth 2.0, PKCE, token introspection, revocation. Any OIDC-compliant library works. | | **13+ database backends** | PostgreSQL, MySQL, MongoDB, DynamoDB, SQLite, and more. Use the database you already run. | --- ### Step-by-Step Setup #### 1. Deploy Authorizer Deploy a single Authorizer instance as your organization's IdP. See the [Deployment guide](/deployment) for options (Docker, Kubernetes, Helm, binary, cloud platforms). Configure the essentials: ```bash authorizer \ --database-type postgres \ --database-url "postgres://user:pass@db:5432/authorizer" \ --url https://auth.yourcompany.com \ --http-port 8080 \ --allowed-origins "https://app1.yourcompany.com,https://app2.yourcompany.com,https://admin.yourcompany.com" \ --organization-name "YourCompany" \ --smtp-host "smtp.yourcompany.com" \ --smtp-port 587 \ --smtp-username "auth@yourcompany.com" \ --smtp-password "..." \ --smtp-sender-email "auth@yourcompany.com" \ --jwt-type RS256 \ --jwt-private-key "$(cat jwt-private.pem)" \ --jwt-public-key "$(cat jwt-public.pem)" \ --encryption-key your-encryption-key \ --client-id YOUR_CLIENT_ID \ --client-secret YOUR_CLIENT_SECRET \ --admin-secret YOUR_ADMIN_SECRET ``` Key flags for SSO: - `--allowed-origins` — Whitelist all app domains that will redirect to Authorizer for login. - `--jwt-type` and `--jwt-secret` / `--jwt-private-key` — Configure token signing (RS256 recommended for multi-app setups since apps verify with the public key via JWKS). - `--encryption-key` — Encrypts TOTP secrets and OTP digests at rest. **Required with `RS*`/`ES*`** (2.4.0+): there is no `--jwt-secret` to fall back to, so the server refuses to start without it. #### 2. Note Your Client Credentials After starting Authorizer, retrieve the `client_id` and `client_secret` from the admin dashboard or server logs. Every app connecting to this Authorizer instance uses these credentials. #### 3. Connect Your Apps Each app needs just four values: ``` OIDC Issuer URL: https://auth.yourcompany.com Client ID: Client Secret: Scopes: openid email profile ``` --- ### Integration Examples #### React / JavaScript App (using authorizer-react SDK) ```jsx import { AuthorizerProvider, Authorizer } from "@authorizerdev/authorizer-react"; function App() { return ( ); } ``` #### Any OIDC-Compliant Library (Generic) ```javascript // Works with openid-client, oidc-client-ts, next-auth, passport-openidconnect, etc. const config = { authority: "https://auth.yourcompany.com", client_id: "YOUR_CLIENT_ID", client_secret: "YOUR_CLIENT_SECRET", redirect_uri: "https://myapp.yourcompany.com/callback", scope: "openid email profile offline_access", response_type: "code", }; // Discovery handles the rest — all endpoints are auto-discovered. ``` #### Server-Side App (Go, Python, Java, etc.) Any language with an OIDC library can connect. The flow: 1. Redirect the user to `https://auth.yourcompany.com/authorize?client_id=...&redirect_uri=...&scope=openid email profile&response_type=code&state=...&code_challenge=...&code_challenge_method=S256` 2. User logs in at Authorizer (or gets silent SSO if already authenticated). 3. Authorizer redirects back to your app with an authorization `code`. 4. Your backend exchanges the code for tokens at `/oauth/token`. 5. Validate the `id_token` using the JWKS from `/.well-known/jwks.json`. #### Third-Party Tools Many tools support "Login with OIDC" out of the box. Examples: | Tool | Configuration | |------|--------------| | **Grafana** | Set `[auth.generic_oauth]` with `auth_url`, `token_url`, `api_url` from Authorizer's discovery endpoint. | | **GitLab** | Use the OmniAuth [OpenID Connect](https://openid.net/specs/openid-connect-core-1_0.html) provider with Authorizer's issuer URL. | | **HashiCorp Vault** | Configure the OIDC auth method with Authorizer as the provider. | | **MinIO** | Set `MINIO_IDENTITY_OPENID_CONFIG_URL` to Authorizer's discovery URL. | | **Kubernetes** | Use `--oidc-issuer-url` flag on the API server for OIDC-based kubectl authentication. | --- ### How Session Sharing Works (Silent SSO) Once a user authenticates with Authorizer, a session cookie is set on the Authorizer domain. When the user navigates to another app: 1. The app redirects to Authorizer's `/authorize` endpoint with `prompt=none`. 2. Authorizer detects the existing session cookie. 3. Authorizer immediately redirects back with an authorization code — **no login screen shown**. 4. The app exchanges the code for tokens. This creates a seamless experience: the user logs in once at Authorizer and is automatically signed into every connected app. #### Force Re-Authentication For sensitive operations, apps can pass `prompt=login` to force the user to re-authenticate even if they have an active session. --- ### Security Features You Get for Free #### Multi-Factor Authentication (MFA) Enable TOTP, email OTP, or SMS OTP globally. Users configure MFA once and it protects access to all apps. #### PKCE (Proof Key for Code Exchange) Enforced for public clients (SPAs, mobile apps). Prevents authorization code interception attacks. Authorizer supports both `S256` and `plain` methods. #### Role-Based Access Control (RBAC) Assign roles to users in Authorizer (e.g., `admin`, `editor`, `viewer`). The `roles` claim is included in every JWT. Each app reads the roles and enforces its own authorization: ```json { "sub": "user_123", "email": "jane@yourcompany.com", "roles": ["admin", "billing"], "iss": "https://auth.yourcompany.com", "aud": "your_client_id" } ``` #### Custom Access Token Claims Use Authorizer's custom access token script (JavaScript) to add app-specific claims to JWTs: ```javascript // Example: add department and team claims from user metadata function(user, tokenPayload) { tokenPayload.department = user.app_data?.department; tokenPayload.team = user.app_data?.team; return tokenPayload; } ``` #### Backchannel Logout When a user logs out from one app, Authorizer can notify all other apps via OIDC Back-Channel Logout. Configure with: ```bash --backchannel-logout-uri "https://app1.yourcompany.com/backchannel-logout" ``` Authorizer sends a signed `logout_token` JWT to the configured URI, allowing all apps to invalidate their local sessions. #### Token Verification Apps can verify tokens in two ways: | Method | When to Use | |--------|-------------| | **JWKS verification** (offline) | Validate JWTs locally using public keys from `/.well-known/jwks.json`. Fast, no network call per request. | | **Token introspection** (online) | Call `/oauth/introspect` to check if a token is still active. Use for refresh token validation or when you need real-time revocation checks. | --- ### Supported Authentication Methods Authorizer supports multiple login methods, all managed centrally: | Method | Description | |--------|-------------| | **Email + Password** | Classic signup/login with email verification | | **Magic Links** | Passwordless login via email link | | **Email OTP** | One-time password sent to email | | **SMS OTP** | One-time password sent via SMS ([Twilio](https://www.twilio.com)) | | **TOTP** | Time-based one-time password (Google Authenticator, Authy) | | **Social Logins** | Google, GitHub, Facebook, LinkedIn, Apple, Discord, Twitter, Microsoft, Twitch, Roblox | Users choose their preferred method. The `amr` (Authentication Methods Reference) claim in the JWT tells your app how the user authenticated: - `pwd` — password - `otp` — magic link or OTP - `fed` — social/federated login --- ### Connecting to Enterprise Identity Providers Authorizer can federate with enterprise identity providers. If your organization already uses Azure AD, Okta, or Google Workspace, users can log in with their corporate credentials through Authorizer's social login configuration: - **Microsoft Azure AD** — Configure with `--microsoft-client-id`, `--microsoft-client-secret`, and `--microsoft-tenant-id`. - **Google Workspace** — Use the standard Google OAuth config. Restrict to your domain via Google's console. Authorizer acts as the intermediary: corporate users log in via their existing IdP, and Authorizer issues unified tokens that all your apps consume. --- ### Response Modes for Different App Types | App Type | Response Mode | How It Works | |----------|---------------|--------------| | **Server-side web apps** | `query` | Authorization code returned as URL query parameter. Most secure. | | **Single Page Apps (SPAs)** | `web_message` | Tokens delivered via HTML5 `postMessage`. No page reload. | | **SPAs (legacy)** | `fragment` | Tokens in URL fragment (implicit flow). | | **Enterprise IdP integrations** | `form_post` | Auto-submitting HTML form POSTs tokens to your server. | --- ### Endpoints Reference All endpoints are auto-discoverable via OIDC Discovery, but here's a quick reference: | Endpoint | Purpose | |----------|---------| | `/.well-known/openid-configuration` | OIDC Discovery — auto-discover all endpoints | | `/.well-known/jwks.json` | Public keys for JWT verification | | `/authorize` | Start login flow (Authorization Code + PKCE) | | `/oauth/token` | Exchange code for tokens / refresh tokens | | `/userinfo` | Get authenticated user's profile | | `/oauth/revoke` | Revoke a refresh token | | `/oauth/introspect` | Check if a token is active | | `/logout` | RP-initiated logout | For detailed endpoint documentation, see the [OAuth 2.0 & OIDC reference](/core/oauth2-oidc). --- ### Enterprise & Workload Identity Features Several capabilities that used to live on this page's roadmap have shipped. Each has its own reference page: #### Client Registry (Multiple Clients) Authorizer maintains a client registry: admins can register additional clients — machine service accounts with their own `client_id`, one-time-revealed `client_secret`, and a per-client scope allow-list — alongside the reserved interactive client. Service accounts authenticate via the OAuth2 `client_credentials` grant. See the [Client Registry guide](./client-registry). > Programmatic *self-service* registration (RFC 7591 Dynamic Client Registration) ships in 2.4.0 but is **off by default** and is scoped to public MCP-style clients — see [Self-registering clients](./mcp#self-registering-clients-cimd-vs-dcr). For everything else, clients are registered by an admin via the admin API or dashboard. #### Organizations Model tenants as organizations with per-org members and per-org roles, and attach per-org SSO and SCIM connections to them. See [Organizations](../enterprise/organizations). #### Per-Organization SAML 2.0 SSO (SP) Authorizer acts as a [SAML 2.0](https://www.oasis-open.org/standard/saml/) Service Provider per organization: register a corporate IdP's entity ID, SSO URL, and signing certificate, and that org's users log in through their IdP with JIT provisioning. See [SAML SSO](../enterprise/org-saml). #### SAML 2.0 Identity Provider (IdP) The architectural inverse of the SP role above: per organization, Authorizer can also act as a **SAML 2.0 Identity Provider**, issuing signed assertions to downstream Service Providers (Zendesk, Salesforce, Notion, …) so their SAML-based SSO logs users in with their existing Authorizer session. Each org gets its own SAML signing keypair with `current` / `active` / `retired` rotation states, and both SP-initiated and opt-in IdP-initiated flows are supported. See [SAML Identity Provider](../enterprise/saml-idp). #### SAML 2.0 Identity Provider (IdP) The architectural inverse of the SP role above: per organization, Authorizer can also act as a **SAML 2.0 Identity Provider**, issuing signed assertions to downstream Service Providers (Zendesk, Salesforce, Notion, …) so their SAML-based SSO logs users in with their existing Authorizer session. Each org gets its own SAML signing keypair with `current` / `active` / `retired` rotation states, and both SP-initiated and opt-in IdP-initiated flows are supported. See [SAML Identity Provider](../enterprise/saml-idp). #### Per-Organization OIDC SSO (Broker) The OIDC sibling of the SAML SP: Authorizer brokers a per-org upstream OIDC IdP (Okta, Entra ID, Google Workspace) as a Relying Party. See [OIDC SSO](../enterprise/org-sso-oidc). #### Verified Domains & Home Realm Discovery Organizations can prove ownership of an email domain — via a DNS TXT challenge, or a trusted-assert shortcut for super-admins — so a login for `jane@acme.com` is automatically routed to Acme's SAML or OIDC connection instead of the generic login form. This routing lookup is called Home Realm Discovery (HRD) and is exposed at the public `/api/v1/org-discovery` endpoint (opt-in, off by default). A verified domain only ever affects routing — it never grants org membership and never blocks login. See [Verified Domains & Home Realm Discovery](../enterprise/org-domains). #### SCIM 2.0 Provisioning (RFC 7644) Per-org inbound [SCIM 2.0](https://datatracker.ietf.org/doc/html/rfc7644) endpoints let enterprise directories (Okta, Microsoft Entra ID, OneLogin) provision and deprovision users automatically. Deactivation synchronously revokes sessions and refresh tokens. See [SCIM Provisioning](../enterprise/scim). #### Workload Identity & Delegation Machines can authenticate without stored secrets (Kubernetes ServiceAccount tokens, [SPIFFE](https://spiffe.io) JWT-SVIDs — see [Workload Identity](../enterprise/workload-identity)), and agents can act on behalf of users with attenuated, audience-bound tokens via [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) token exchange (see [Token Exchange](../enterprise/token-exchange)). --- ### Future Roadmap Still planned for future releases: #### Dynamic Client Registration (RFC 7591) Self-service programmatic client registration (the `registration_endpoint`) is available from 2.4.0 behind `--enable-dynamic-client-registration`, and is deliberately narrow: it registers **public** clients only, for the MCP onboarding case. Confidential clients are still created by an admin through the [client registry](./client-registry) admin API. See [Self-registering clients](./mcp#self-registering-clients-cimd-vs-dcr). #### LDAP / Active Directory Integration Direct LDAP/AD integration will allow Authorizer to authenticate users against existing corporate directories without requiring federation through Azure AD or Google Workspace. #### Front-Channel Logout (OIDC) In addition to the already-supported backchannel logout, front-channel logout will add browser-based logout propagation via hidden iframes for apps that cannot expose a backchannel endpoint. #### Automated JWKS Key Rotation Time-based automatic rotation of JWT signing keys with configurable rotation periods, eliminating the need for manual key rotation. (Zero-downtime *manual* rotation via secondary keys is already supported — see the [OAuth 2.0 & OIDC reference](/core/oauth2-oidc).) --- ### Summary Authorizer gives you a **self-hosted, single-binary SSO server** that speaks standard OIDC. Any app — internal tool, customer portal, or third-party service — can authenticate against it. Users get one account, one login, one MFA setup. You get full control over your identity data with no per-user SaaS fees. | What You Get Today | What's Coming | |---|---| | Full OIDC IdP with discovery | Dynamic client registration for *confidential* clients (RFC 7591 covers public clients only) | | 10+ social login providers | LDAP/AD integration | | MFA (TOTP, email OTP, SMS OTP) | Front-channel logout | | RBAC with JWT claims | Automated JWKS rotation | | Backchannel logout | | | Token introspection & revocation | | | 13+ database backends | | | Custom access token scripts | | | [Client registry](./client-registry) + `client_credentials` grant | | | [Organizations](../enterprise/organizations) with per-org members & roles | | | [Per-org SAML 2.0 SP](../enterprise/org-saml), [SAML 2.0 IdP](../enterprise/saml-idp) & [OIDC broker SSO](../enterprise/org-sso-oidc) | | | [Verified domains & Home Realm Discovery](../enterprise/org-domains) | | | [SCIM 2.0 provisioning](../enterprise/scim) | | | [Workload identity](../enterprise/workload-identity) (K8s, SPIFFE) | | | [RFC 8693 token exchange](../enterprise/token-exchange) (delegation) | | --- ## Agent Identity & Permissions [Token exchange](./token-exchange) gives you a token that carries **both** identities — `sub` is the user, `act.sub` is the agent. This page is about what Authorizer then *does* with that second identity when the agent asks a permission question. The short version: an agent's effective authority is the **intersection** of its own permissions and its user's. ``` effective authority = perms(agent) ∩ perms(user) ``` Evaluated per action, at request time, on both `check_permissions` and `list_permissions`. ### Why an intersection Give an agent a token and it holds the user's authority. Give it its own grants and it holds those. Neither alone is safe: - **Only the user's authority** — a compromised or confused agent can do anything its user can. The classic [Confused Deputy](https://en.wikipedia.org/wiki/Confused_deputy_problem): a calendar-reading agent tricked into reading payroll, because its user *can* read payroll. - **Only the agent's authority** — the agent acts on resources its user was never allowed near, and "on behalf of Alice" becomes a fiction. Intersecting both means an agent can only ever do things that **it** is trusted with **and** that its **user** could have done themselves. Neither identity can widen the other. This matches how WorkOS, Auth0 FGA and [OpenFGA](https://openfga.dev) model agentic access. ### Turning it on **Declare `type agent` in your authorization model.** That is the whole opt-in — there is no flag to enable it. ```dsl model schema 1.1 type user type agent type document relations define viewer: [user, agent] define can_view: viewer ``` Declaring the type IS the opt-in because the feature is meaningless without a model that can express agent grants, and because of how OpenFGA fails: checking `agent:x` against a model with **no** `agent` type does not return `false`, it **errors** — and permission checks fail closed on errors. A flag that could be switched on against an unprepared model would deny every permission check for every delegated caller: a total authorization outage, not a graceful degradation. Auto-detection makes that state unreachable. Detection is cached per authorization-model id, so writing a new model version takes effect immediately. The model-id lookup itself still runs per delegated request; only the type enumeration is cached. :::info What happens before you declare the type (changed in 2.4.0) A delegated check against a model with **no** `type agent` is now **denied**. Before 2.4.0 it authorized as the delegating user alone, which silently dropped the agent half of the intersection. If that denial blocks you mid-migration, [`--fga-allow-unconstrained-agents`](../core/server-config#--fga-allow-unconstrained-agents) restores the old behaviour — with the agent carrying its user's full authority, logged and metered on every request. It is a migration aid, not a setting to leave on. ::: :::note Before you declare the type The moment `type agent` appears in your model, every delegated caller must ALSO satisfy the agent half. Grant your agents before you deploy the model, or their calls start being denied. The [`denied_by_agent` metric](#observability) tells you exactly this is happening. ::: ### Granting an agent The agent's subject is `agent:` — the `client_id` of the [`service_account`](../core/client-registry) that authenticated the exchange, which is the same value that appears as `act.sub` on the token. Grant it like any other subject: ```bash # Alice can view the document curl … -d '{"query":"mutation { _fga_write_tuples(params: { tuples: [ { user: \"user:alice-id\", relation: \"viewer\", object: \"document:q4-plan\" } ]}) { message } }"}' # The calendar agent may view it too curl … -d '{"query":"mutation { _fga_write_tuples(params: { tuples: [ { user: \"agent:calendar-agent-client-id\", relation: \"viewer\", object: \"document:q4-plan\" } ]}) { message } }"}' ``` Now `check_permissions` with a delegated token returns `allowed: true` only while **both** tuples exist. Delete either one and it is `false`. #### One user, many agents Agents are independent subjects, so a user can delegate to as many as they like and each carries its own, separately revocable reach: | Grant | Effect | |-------|--------| | `agent:calendar-bot` → `viewer` on `document:*` | that agent may read documents Alice can read | | `agent:finance-bot` → nothing | that agent can do nothing for Alice, whatever her own access | Revoking one agent's tuple does not touch the user or any other agent. #### Time-limited and task-scoped grants Agent access usually shouldn't be permanent. Use a [condition](../core/fga-guide#conditions-cel--with) so a grant expires by itself, and a `task` type so a whole task's access is granted and revoked in one place. This template is also in the dashboard's model examples as **AI agents (time-limited & task-scoped)**: ```dsl model schema 1.1 type user type agent type task relations define assignee: [agent] type tool relations define can_call: [user, agent with non_expired_grant, task#assignee with non_expired_grant] condition non_expired_grant(current_time: timestamp, grant_time: timestamp, grant_duration: duration) { current_time < grant_time + grant_duration } ``` ```text # Direct: the calendar agent may call tool:search for 10 minutes agent:calendar-bot can_call tool:search with non_expired_grant {grant_time: "2026-11-27T10:00:00Z", grant_duration: "10m"} # Task-scoped: every agent assigned to task:t-42 may call tool:deploy for 10 minutes agent:deploy-bot assignee task:t-42 task:t-42#assignee can_call tool:deploy with non_expired_grant {grant_time: "2026-11-27T10:00:00Z", grant_duration: "10m"} ``` Delete `task:t-42#assignee can_call tool:deploy` to end the task for every agent at once. The users who delegate need their own `can_call` grants too: a delegated check passes only when the agent **and** the user are allowed. The server's clock decides expiry. An agent can't extend its own window: a delegated token may not send condition `context` or contextual tuples to `check_permissions`, and requests that try are rejected. #### Agent-to-agent (multi-hop) Only the **immediate** actor participates in the decision. In a chain `app → agent → sub-agent`, the check is `perms(sub-agent) ∩ perms(user)` — prior actors nested deeper in `act` are recorded for audit but never grant or deny. They were asserted upstream, not verified here, so treating them as authority would let a middle hop vouch for itself. Since scope attenuation is monotonic across hops (see [token exchange](./token-exchange#scope-attenuation)), a longer chain can only ever be narrower. ### Calling Authorizer's own API A delegated token is bound to exactly one `resource` (RFC 8707) and is only accepted there. To let an agent ask **Authorizer** about its own authority, exchange for Authorizer's own URL: ```bash curl -X POST $AUTHORIZER_URL/oauth/token \ -u "$AGENT_CLIENT_ID:$AGENT_CLIENT_SECRET" \ -d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \ -d "subject_token=$USER_ACCESS_TOKEN" \ -d "subject_token_type=urn:ietf:params:oauth:token-type:access_token" \ -d "actor_token=$AGENT_TOKEN" \ -d "actor_token_type=urn:ietf:params:oauth:token-type:access_token" \ -d "resource=$AUTHORIZER_URL" # ← Authorizer itself ``` Present the result as a normal bearer token: ```graphql query { check_permissions(params: { checks: [{ relation: "can_view", object: "document:q4-plan" }] }) { results { relation object allowed } # intersected: agent AND user } } ``` A token exchanged for `https://calendar.example` will **not** authenticate here, and vice versa. That is the audience binding doing its job, not a misconfiguration. ### What an agent may do: scope The intersection above decides **which resources** an agent may reach. A second, independent gate decides **which operations** it may call at Authorizer's own API — the token's `scope` claim, enforced per operation. | Operation | Required scope | |---|---| | `check_permissions`, `list_permissions` | `openid` | | `profile`, `meta` | `openid` | | `update_profile` | `authorizer:profile:write` | | `deactivate_account` | `authorizer:account:delete` | | anything else | **denied** — see below | Read-only identity and permission queries need only `openid`, which every token carries, so the questions an agent must be able to ask to function at all just work. That set is exactly the [MCP](../core/mcp) tool surface. Mutating operations need a scope **no client requests by default**. Since a delegated token's scope is `subject_token.scope ∩ agent.allowed_scopes`, granting one takes *both* parties: 1. the delegating user's own token must carry the scope (request it at login), **and** 2. an admin must add it to the agent's `allowed_scopes` ceiling. Neither can widen an agent alone. A refusal is `insufficient_scope` ([RFC 6750 §3.1](https://www.rfc-editor.org/rfc/rfc6750#section-3.1)). :::note Fail closed by default Any operation not in that table is **denied to delegated callers**, whatever scope they hold. New operations are therefore unreachable by agents until someone deliberately clears them — the opposite of an allowlist that quietly widens when a contributor forgets to update it. ::: #### Why first-party tokens are not gated A first-party `scope` is whatever the client asked for at login — it is not validated against an allow-list — so it is a hint, not a boundary. Enforcing it would break existing clients and buy no security. A delegated token is different: its ceiling comes from `allowed_scopes` on the agent's `service_account`, which only an admin can set. That is what makes the same claim a real boundary, and it is the same asymmetry Microsoft draws between delegated and application permissions. #### The subject cannot be changed `check_permissions` and `list_permissions` accept an optional `user`. For a delegated caller it may only ever be the caller's own subject — supplied or not, the agent half is still applied. Naming any other subject is rejected outright, even if the request also carries an admin credential. An agent must not be able to shed its own constraint, or probe access that neither half of its intersection has. ### Revocation | Lever | Stops a delegated token at Authorizer's API? | Stops it at a downstream resource server? | |-------|---|---| | Its 5-minute TTL expiring | Yes | Yes | | User logs out (that session) | Yes | No | | Password reset / email change | Yes | No | | Admin wipes the user's sessions | Yes | No | | User revoked or deprovisioned ([SCIM](./scim) `active:false`) | Yes | No | | Service-account subject deactivated | Yes | No | | Deleting the agent's FGA tuples | Yes — the next check denies | n/a | | **The agent's own service account deactivated** | **No** — see below | No | :::warning Deactivating the agent does not stop tokens it already holds Only the **subject** is checked for liveness at validation time; the acting agent is not. Deactivating an agent's service account blocks the **next** exchange, but a token it minted moments earlier keeps working until its 5-minute TTL expires. Do not treat "disable the agent" as immediate containment — to cut an agent off now, delete its FGA tuples, which the very next check honours. ::: A delegated token carries an opaque `sid` naming the session it was derived from, so at Authorizer's own API it is exactly as revocable as the credential that seeded it. A **downstream resource server** verifies the token offline against [`/.well-known/jwks.json`](../core/oauth2-oidc) and cannot see any of that — there, the short TTL remains the only bound. Keep it that way: do not build a resource server that treats a delegated token as long-lived. ### Audit A delegated action is recorded as the **agent**, with the user preserved alongside: | Field | Value | |-------|-------| | `actor_id` | the agent's `client_id` | | `actor_type` | `agent` | | `actor_email` | *(empty — an agent has no mailbox)* | | `metadata` | gains `delegated_user_id=…` and, when known, `delegated_user_email=…` | Without this an agent's actions are indistinguishable from the user's own — same id, same type, no trace anything automated was involved. [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) §1.1 draws exactly this line: delegation is "A representing B" with A keeping its identity, as against impersonation where A is indistinguishable from B. It cannot be reconstructed after the fact, because the information was never written. ### Observability {#observability} `authorizer_fga_delegated_checks_total{operation, outcome}` counts every delegated decision. The `outcome` label is what makes an intersection denial diagnosable: | `outcome` | Meaning | What to do | |-----------|---------|-----------| | `allowed` | both halves permitted | — | | `denied_by_agent` | the agent has no grant; the user may well have access | grant the **agent** a tuple | | `denied_by_user` | the agent had its grant, the user does not have access | **do not** widen the agent — this is the Confused Deputy case working as intended | | `not_enforced` | a delegated caller arrived but the model declares no `agent` type, so the agent half could not be evaluated | declare `type agent` and grant your agents | `not_enforced` is the one to alert on, and it means one of two things depending on [`--fga-allow-unconstrained-agents`](#turning-it-on): - **Default (flag unset):** the check was **denied**. Agents are failing against a model that cannot express agent grants — a misconfiguration, not an attack. Users will report it as a broken integration; this counter tells you why. - **Flag set:** the check was authorized as the **delegating user alone**, with the agent unconstrained. That is silent by construction — the request succeeds and nothing in the response says so. Treat a non-zero rate here as exposure with a clock on it, not a steady state. Either way the remedy is the same: add `type agent` to the model and grant the agents. `allowed`, `denied_by_agent` and `denied_by_user` are emitted by **`check_permissions` only**. `list_permissions` intersects object *sets* rather than folding a per-check decision, so the only outcome it can ever report is `not_enforced`. Ordinary (non-delegated) callers do not appear in this series at all; they are counted in `authorizer_fga_checks_total` exactly as before. ### What does not change Delegation is additive. If your model has no `agent` type, every one of these behaves precisely as it did before: - OIDC, SAML, SCIM, OAuth 2.1 flows and `client_credentials` (M2M). - `check_permissions` / `list_permissions` for user and service-account callers. - A machine token still resolves to `service_account:`. A delegated token resolves according to **its subject**: a token delegating a *user* resolves to `user:` (the common app-acting-for-user case), and a token delegating a *service account* — the agent-to-agent chain — resolves to `service_account:`. Before 2.4.1 the second case incorrectly resolved to `user:`, which is [GHSA-vq29-8q3c-3hrm](https://github.com/authorizerdev/authorizer/security/advisories/GHSA-vq29-8q3c-3hrm); if you wrote tuples against `user:` to work around it, move them to `service_account:`. ### Failure modes Everything fails closed: | Situation | Result | |-----------|--------| | The model cannot be read to detect the agent type | the delegated request is **denied** (ordinary callers are unaffected) | | The engine errors on any check | the whole call is denied | | The agent's `client_id` has an unexpected shape | denied — it is never concatenated into a subject string unchecked | | The delegating user cannot be confirmed active | denied | | The originating session is gone | denied | ### See also - [Token Exchange & Delegation](./token-exchange) — how the token is minted, scoped and chained - [Authorization (FGA)](../core/authorization) — the model, tuples and the permission APIs - [Client Registry](../core/client-registry) — registering an agent as a `service_account` - [`with-agent-permissions`](https://github.com/authorizerdev/examples/tree/main/with-agent-permissions) — **runnable demo of everything on this page**: the intersection, enumeration, the explicit-`user` gate, per-agent revocation, and the model-declares-agent opt-in - [`with-agent-delegation`](https://github.com/authorizerdev/examples/tree/main/with-agent-delegation) — runnable multi-hop example of minting the token itself (scope attenuation, `act` chain) --- ## Human Approval for Agent Actions (CIBA) ## Human approval for agent actions (CIBA) :::info Beta OpenID CIBA (poll mode) is available from Authorizer **2.5.0** as a beta, off by default. ::: Some actions should not ride on a grant made in advance: *send this payment*, *delete this repository*, *email this customer*. With CIBA (OpenID [Client-Initiated Backchannel Authentication](https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html) Core 1.0), an agent asks the user to approve **that** action, **now**, and only gets authority for it after they say yes. ### Which path do you need? | Your agent… | Use | |---|---| | can open the user's browser (Claude Code, Cursor, a desktop or CLI agent) | [Step-up with `/authorize`](#agents-that-can-open-a-browser-step-up) — no CIBA needed | | runs without the user present (background job, queue worker, chat or email bot, cloud agent) | [CIBA](#how-ciba-works) | ### Agents that can open a browser: step-up A desktop agent already opens the user's browser for MCP OAuth. To require a fresh sign-in before a sensitive action, send the user through `/authorize` again with `prompt=login` (or `max_age=0`): ``` GET /authorize?response_type=code&client_id=...&redirect_uri=... &scope=openid&prompt=login&code_challenge=...&code_challenge_method=S256 ``` Authorizer ends the current session and asks for credentials again, with MFA when the user is enrolled. The ID token's `auth_time` is the new sign-in time; check it, then use the fresh user token for [token exchange](./token-exchange) as usual. Limits: the user sees a sign-in, not the action, and `auth_time` is on the ID token only — the resource server cannot see it. When the user must approve a specific action, or isn't at the agent's screen, use CIBA. ### How CIBA works ``` Agent (service account) Authorizer User POST /oauth/bc-authorize ─► request stored, link sent ──────► email / your app (webhook) ◄── auth_req_id opens link, signs in, POST /oauth/token (poll) ─► authorization_pending reviews the action, ... ◄──────── Approve / Deny POST /oauth/token (poll) ─► access_token (5 min, bound to the action) + id_token ``` - The agent names the user and describes the action (`binding_message`, optional [RFC 9396](https://www.rfc-editor.org/rfc/rfc9396) `authorization_details`). - The user approves on **Authorizer's own page**, signed in with their own session. No OAuth client — not even the agent's own UI holding the user's token — can approve for them. - The agent receives a delegated token that works at **one** external API, for **five minutes**, and says exactly what was approved. ### Enable it **1. Server flags** ```bash ./authorizer \ --url=https://auth.example.com \ --enable-ciba \ --ciba-authorization-details-types=payment_initiation # optional ``` | Flag | Default | Meaning | |---|---|---| | `--enable-ciba` | `false` | Serves `/oauth/bc-authorize`, the approval page `/oauth/bc-approve`, the CIBA grant, and advertises them in discovery. | | `--ciba-request-ttl` | `300` | Request lifetime in seconds (1–600). `requested_expiry` can shorten it. | | `--ciba-poll-interval` | `5` | Minimum seconds between polls (2–60). | | `--ciba-max-requests-per-user` | `3` | Requests one agent may make for one user per request-TTL window. | | `--ciba-max-requests-per-user-total` | `10` | Requests all agents together may make for one user per window. | | `--ciba-step-up-max-age` | `300` | The user must have signed in within this many seconds to approve. | | `--ciba-authorization-details-types` | empty | RFC 9396 types accepted. Empty refuses any `authorization_details`. | Requirements: - `--url` must be `https` (CIBA requires TLS); `http` is accepted on `localhost` for development. - A way to reach users: SMTP (the `ciba_approval` email), or a webhook for `user.approval_requested`, or both. - With an explicit `--allowed-origins` list, include the server's own origin so the login page can return users to the approval page. **2. Register the agent for CIBA** The agent is a `service_account` [client](../core/client-registry) with `openid` in its allowed scopes. Turn CIBA on per client in the dashboard (**Clients → Human approval (CIBA)**) or the admin API: ```graphql mutation { _update_client(params: { id: "", backchannel_token_delivery_mode: "poll" }) { client_id backchannel_token_delivery_mode } } ``` `"poll"` enables CIBA, `""` disables it. Dynamically registered and metadata-document clients can never use CIBA. ### Request an approval ```bash curl -s -u "$CLIENT_ID:$CLIENT_SECRET" https://auth.example.com/oauth/bc-authorize \ -d scope="openid payments:write" \ -d login_hint="$USER_ID" \ -d binding_message="Pay \$40 to Acme Corp" \ -d resource="https://api.example.com/payments" \ --data-urlencode 'authorization_details=[{"type":"payment_initiation","amount":40,"currency":"USD","creditor":"Acme Corp"}]' ``` ```json { "auth_req_id": "…", "expires_in": 300, "interval": 5 } ``` | Parameter | Rules | |---|---| | `scope` | Must include `openid`. Narrowed to the client's allowed scopes. `authorizer:*` scopes are refused. | | `login_hint` *or* `id_token_hint` | Exactly one. `login_hint` is the user's Authorizer user id. `id_token_hint` is an ID token Authorizer issued **to this client** (for example from an earlier CIBA approval), accepted up to 30 days after it expired. Email and phone hints are not supported. | | `binding_message` | **Required.** Up to 64 characters of plain text; shown to the user as the agent's own words. | | `resource` | **Required, exactly one.** An absolute URI of the API the token is for; becomes the token's `aud`. A URI on Authorizer's own host and port is refused (`invalid_target`); the default ports `:80` and `:443` count as the same, and a trailing dot on the host is ignored. On `localhost`, use a different port from Authorizer's. | | `authorization_details` | Optional. A JSON array (≤ 5 objects, ≤ 4 KB) whose `type`s are in `--ciba-authorization-details-types`. Values are strings, numbers, booleans or arrays of strings. | | `requested_expiry` | Optional, seconds; may only shorten the request. | Clients authenticate as at the token endpoint: client secret, or a [workload-identity assertion](./workload-identity) (recommended — CIBA advises against shared secrets). At `/oauth/bc-authorize`, when the trusted issuer's expected audience is one of Authorizer's own URLs, an assertion carrying the issuer, token endpoint or backchannel endpoint URL as its `aud` is accepted (CIBA §7.1). Polling `/oauth/token` still requires the expected audience exactly, so give your assertions that audience (typically the token endpoint URL). :::note No user enumeration A request for a user who cannot be asked — unknown, revoked, outside the agent's organization, over a cap, or blocked — gets the same `200` response and simply never gets approved (it ends in `expired_token`). Authorizer never returns `unknown_user_id`. ::: ### Poll for the result ```bash curl -s -u "$CLIENT_ID:$CLIENT_SECRET" https://auth.example.com/oauth/token \ -d grant_type=urn:openid:params:grant-type:ciba \ -d auth_req_id="$AUTH_REQ_ID" ``` | Response | Meaning | |---|---| | `authorization_pending` | Not decided yet. Poll again after `interval` seconds. | | `slow_down` | Polled too fast. Add 5 seconds to your interval for this request. | | `access_denied` | The user denied, or the user was revoked after approving. | | `expired_token` | Nobody decided in time. Start a new request. | | `invalid_grant` | Unknown `auth_req_id`, another client's, or already redeemed. | | `200` | Approved: tokens below. Each approval can be redeemed once. | ```json { "access_token": "…", "token_type": "Bearer", "expires_in": 300, "id_token": "…", "scope": "openid payments:write", "authorization_details": [{ "type": "payment_initiation", "amount": 40, "currency": "USD", "creditor": "Acme Corp" }] } ``` No refresh token: one approval, one action. ### Verify the token at your API The access token is a JWT signed by Authorizer (verify against `/.well-known/jwks.json`): ```json { "iss": "https://auth.example.com", "sub": "", "aud": "https://api.example.com/payments", "act": { "sub": "" }, "client_id": "", "scope": ["openid", "payments:write"], "authorization_details": [{ "type": "payment_initiation", "amount": 40, "currency": "USD", "creditor": "Acme Corp" }], "ciba": { "req": "", "msg": "", "approved_at": 1764500000 }, "exp": 1764500300 } ``` Before acting, your API should check: 1. signature, `iss`, `exp`, and `aud` equals **your** API's URL; 2. `act.sub` is the agent you expect; 3. the operation matches `authorization_details` — approving "$40 to Acme" must not authorize "$4,000 to someone else"; 4. optionally, `ciba.msg` matches the SHA-256 of the binding message you expected; 5. the approval has not been used already: the token stays valid for its five minutes, so record `ciba.req` (or `jti`) until `exp` and refuse a repeat if the action must happen once. `checkApprovedAction` (authorizer-js) and `check_approved_action` (authorizer-py) implement checks 2–4 on claims you have already verified. The token has no `sid`, so it is refused by Authorizer's own APIs. ### What the user sees The email (or your app, via the webhook) links to `/oauth/bc-approve?id=…`. The page: - asks the user to sign in if needed, and again if their sign-in is older than `--ciba-step-up-max-age` or was by magic link. Signing in again ends the user's current Authorizer session first, so opening an approval link some time after signing in signs the user out of other apps that share that session (the link itself arrived by email, so a mailbox-only sign-in proves nothing new). Other ways in that rely on the mailbox — an email-verification link, or a password reset — still count; enable MFA for users who approve high-value actions; - shows the agent's registered name, the action details and the binding message (both labelled as the agent's own, *not verified*), the API and the scopes; - offers **Approve**, **Deny** (the agent can't ask this user again for an hour) and **Deny and block this agent** (24 hours). Customize the email under **Email Templates → CIBA approval request** (`{{.agent_name}}`, `{{.binding_message}}`, `{{.approval_url}}`, `{{.expires_in_minutes}}`, `{{.resource}}`). #### Deliver it through your own app: the webhook Register a webhook for **`user.approval_requested`** to push the request to your own channel (mobile push, chat). The payload carries the `user` and: ```json "approval_request": { "approval_url": "https://auth.example.com/oauth/bc-approve?id=…", "agent": { "client_id": "…", "name": "Payments agent" }, "binding_message": "Pay $40 to Acme Corp", "authorization_details": [ … ], "scopes": ["openid", "payments:write"], "resource": "https://api.example.com/payments", "expires_at": 1764500300 } ``` The link is a lookup handle, not a credential: approving still needs the user's own signed-in session. Verify the `X-Authorizer-Signature` header, an HMAC-SHA256 of the request body keyed with Authorizer's `--client-secret`, before you show the link to anyone. #### Show it inside an MCP client: URL elicitation When the agent is an MCP server and the user is at the MCP client, the server can show the approval link right there. To do this it uses [URL-mode elicitation](https://modelcontextprotocol.io/specification/2025-11-25/client/elicitation): it receives the link on the webhook above and sends it to the client with `elicitation/create` (`mode: "url"`). Name the user in `login_hint` from the `sub` of the MCP caller's own token, so the person who opens the link is the only one who can approve. Put a short reference in the binding message so that you can match the webhook to the tool call and the user can match the page to the client. The [with-ciba example](https://github.com/authorizerdev/examples/tree/main/with-ciba) has a working server and client. ### Monitor it - Audit events: - `ciba.requested`, `ciba.approved`, `ciba.denied`, `ciba.blocked` and `ciba.token_issued`. - `ciba.expired`, written the first time the agent polls a request that expired undecided. A request the agent never polls again leaves only `ciba.requested`. - Only requests that could reach a user are recorded. - Prometheus: - `authorizer_ciba_outcomes_total{client_id, outcome}`, where `outcome` is `approved`, `denied`, `blocked` or `expired`. Alert on a high deny rate per agent: ```promql sum by (client_id) (rate(authorizer_ciba_outcomes_total{outcome=~"denied|blocked"}[1h])) / sum by (client_id) (rate(authorizer_ciba_outcomes_total[1h])) ``` - `authorizer_ciba_time_to_decision_seconds{outcome}`: how long users take to decide. - `authorizer_security_events_total{event="ciba_channel_failed", reason="email"|"webhook"}`: approval requests that could not be delivered. ### Security summary - Only opted-in service accounts can start a request; only the user, in their own recent session, on Authorizer's page, can approve. - Organization-scoped agents can only reach members of their organization. - Per-agent and per-user caps, blocks after a deny, and a per-client rate limit (60 requests/minute) bound approval fatigue. - Tokens are delegated, bound to one external API and the approved action, valid five minutes, never usable at Authorizer itself, and cannot be [exchanged](./token-exchange) for an unbound token. - Every request, decision, expiry and token issuance is audited ([Monitor it](#monitor-it)). Not supported yet: ping and push delivery, `user_code`, signed requests, email or phone hints. --- ## Verified Domains & Home Realm Discovery A **verified domain** proves that an [organization](./organizations) controls an email domain (`acme.com`), so a login for `jane@acme.com` can be automatically routed to Acme's SSO connection instead of showing the generic login form. This routing lookup is called **Home Realm Discovery (HRD)**, sometimes called "organization discovery." ### The one rule that matters: domain ≠ membership A verified domain answers exactly one question — **"which org's SSO should a login for this email route to"** — and nothing else. It never determines: - **Who is a member.** Membership comes only from an explicit `OrgMember` row (via [`_add_org_member`](./organizations#manage-members), SSO JIT-provisioning, or SCIM). An external consultant `jane@consulting-firm.com` can be a full member of Acme even though `consulting-firm.com` is not a verified Acme domain. - **Whether login is allowed.** A user whose email domain matches no verified domain is not blocked — they just don't get an SSO redirect, and fall back to whatever their membership already permits (password, social, magic link, or an SSO connection they access some other way). - **What happens if a member's email domain changes.** Membership and roles are untouched — they were never keyed on the domain string. Deleting a verified domain only removes the routing hint. It never removes members, and it never revokes access. ### How a domain gets verified Two methods ship today: | Method | Who can use it | Proof required | Operation | |--------|-----------------|-----------------|-----------| | **DNS TXT challenge** | Org admin (or super-admin) | Publish a TXT record at a specific name | `_request_org_domain` then `_verify_org_domain` | | **Trusted assert** | Super-admin only | None — the platform operator is already trusted | `_add_verified_org_domain` | There is no auto-verify-by-owned-mailbox shortcut and no email-OTP-to-domain method in the current release — both were considered during design but did not ship. DNS TXT is the only self-serve proof path; trusted-assert is the operator escape hatch (used by the dashboard's "Add without DNS verification" quick-add for super-admins). A verified domain is a row **only once proven** — a pending DNS challenge is not a database row, it's a short-lived token in the memory store (~24h TTL) and is never used for routing until it's matched. ### Admin GraphQL operations All are org-scoped-admin gated (super-admin, or that org's `authorizer:org_admin` member) except `_add_verified_org_domain`, which is super-admin only: | Operation | Type | Purpose | |-----------|------|---------| | `_request_org_domain` | mutation | Mint a DNS TXT challenge for `org_id` + `domain` | | `_verify_org_domain` | mutation | Check the TXT record and, on match, insert the verified row | | `_add_verified_org_domain` | mutation | **Super-admin only.** Insert a verified row with no proof (trusted-assert) | | `_org_domains` | query | Paginated list of an org's verified domains (never another org's) | | `_delete_org_domain` | mutation | Remove a verified mapping, freeing the domain for re-verification | #### DNS TXT walkthrough **1. Request a challenge:** ```graphql mutation { _request_org_domain(params: { org_id: "ORG_ID", domain: "acme.com" }) { domain record_type record_name record_value } } ``` Response: ```json { "data": { "_request_org_domain": { "domain": "acme.com", "record_type": "TXT", "record_name": "_authorizer-challenge.acme.com", "record_value": "authorizer-domain-verification=<32-byte base32 token>" } } } ``` **2. Publish the record**, then confirm it resolves: ```bash dig +short TXT _authorizer-challenge.acme.com # "authorizer-domain-verification=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` **3. Verify:** ```graphql mutation { _verify_org_domain(params: { org_id: "ORG_ID", domain: "acme.com" }) { domain org_id verified_at } } ``` The match is an **exact string comparison** against `authorizer-domain-verification=` — a substring/prefix match is deliberately not accepted. If the record isn't visible yet, `_verify_org_domain` returns a "dns verification failed" error and **leaves the challenge in place** so you can retry once DNS propagates; it does not require re-requesting a new token. The DNS lookup is TXT-only with a bounded ~5s timeout — no HTTP fetch is ever made against the domain. #### Trusted-assert (super-admin) ```graphql mutation { _add_verified_org_domain(params: { org_id: "ORG_ID", domain: "acme.com" }) { domain org_id verified_at } } ``` Skips the DNS challenge entirely. Only a super-admin can call this — an org admin attempting it is rejected. Still subject to the same uniqueness and public-suffix guards as DNS verification (see below). #### List and delete ```graphql query { _org_domains(params: { org_id: "ORG_ID", pagination: { limit: 100 } }) { pagination { total } org_domains { domain verified_at } } } ``` ```graphql mutation { _delete_org_domain(params: { domain: "acme.com" }) { message } } ``` `_delete_org_domain` takes only the domain — the owning org is loaded from the row first, and the org-admin check is authorized against *that* org, not a caller-supplied `org_id`. ### Home Realm Discovery endpoint ``` GET /api/v1/org-discovery?email= ``` Public, unauthenticated, and gated behind the `--enable-org-discovery` flag (**default `false`** — off until an operator opts in; a single-tenant deployment with no per-org SSO never needs it). When disabled, the endpoint returns `404`. The response is deliberately minimal to avoid letting a caller enumerate your tenant list by probing domains: ```json // match with SSO connection { "connection": { "type": "saml", "login_url": "/oauth/saml/acme/login" } } ``` ```json // verified domain but no SSO connection, OR no match at all — indistinguishable { "connection": null } ``` Nothing beyond `login_url` (which necessarily embeds the org's slug) is ever returned — no `organization_id`, `organization_name`, or `org_id`, and there's no operator "verbose" opt-in to add them. If the org has both an active SAML and an active OIDC connection, SAML takes precedence. A pending (unverified) domain is never resolved — `GetOrgDomainByDomain` is a lookup against verified rows only, so it's structurally impossible for an in-flight challenge to affect routing. The endpoint has its own per-IP rate limit bucket, independent of the global request limiter, to blunt domain-enumeration attempts; a malformed `email` returns a uniform `400` with no parsing detail. ### `/app` login page integration The hosted login page (`/app`, gated by `--enable-login-page`) shows an email-first step when discovery is enabled: 1. The user types their email and submits. 2. The SPA calls `GET /api/v1/org-discovery?email=…`. 3. **SSO match** — the browser is redirected to `connection.login_url`, with the original `redirect_uri` and `state` appended so the post-login flow returns to your app, not to `/app`. 4. **No match (or discovery disabled/erroring)** — the standard password/social/magic-link login renders inline, exactly as it does today. Discovery is a routing hint only; it never blocks or fails a login. This flag is opt-in per deployment (`--enable-org-discovery`, mirrored to the SPA as `Meta.is_org_discovery_enabled`); leaving it off keeps `/app` byte-for-byte the same as before this feature existed. #### App-supplied escape hatch If your app already knows which org a user belongs to (a subdomain, an org picker, your own domain-to-tenant map), skip discovery entirely and send the user straight to that org's login: ``` GET /oauth/saml/{org_slug}/login?redirect_uri=...&state=... ``` or the [OIDC broker](./org-sso-oidc) equivalent. This is the recommended path whenever your app already owns the org mapping — HRD exists for the case where it doesn't. ### Dashboard UX The org detail page's **Verified Domains** panel: a table of the org's verified domains with their verification date, an **Add Domain** dialog that walks through request → show the DNS record with copy-to-clipboard → verify (with a retryable "not propagated yet" hint on failure), and a super-admin-only "Add without DNS verification" quick path. Each row has a **Delete** action. ### Security & behavior reference | Behavior | Detail | |----------|--------| | **Public-suffix / consumer guard** | Bare TLDs and multi-label public suffixes (`com`, `co.uk`) are rejected, plus a blocklist of major consumer providers (`gmail.com`, `outlook.com`, `icloud.com`, …) even where the public-suffix list would technically allow them. | | **Uniqueness** | The normalized domain is the row's primary key — one verified domain routes to exactly one org, enforced atomically at the storage layer (not a check-then-insert race). A second org verifying an already-claimed domain gets a `domain_already_verified_by_another_org` error; re-verifying your own already-verified domain is a no-op success. | | **Subdomains are exact-match** | Verifying `acme.com` does **not** cover `eng.acme.com` — each (sub)domain is its own row, matching the DNS challenge's exact-name granularity. | | **Normalization** | One shared normalizer (IDNA/UTS-46, lowercased, punycode, no scheme/path/port/wildcard) is used for both writes and HRD lookups, so a login email resolves to the exact stored value. | | **Org-delete cascade** | Deleting an organization cascades to delete its verified domains, freeing them for re-claim by anyone. Without this a deleted org's domain would be permanently unclaimable, since the domain is the primary key. | | **Rate limiting** | `_request_org_domain` and `_verify_org_domain` are rate-limited per org; the public `/api/v1/org-discovery` endpoint is rate-limited per IP, separately from the global request limiter. | | **Token secrecy** | The DNS challenge token is never logged; only the verification *method* (`dns_txt` / `trusted_assert`) is recorded in the audit event, never the token value. | | **Multi-instance deployments** | The pending DNS challenge lives in the memory store, which is per-node unless Redis is configured — the same requirement as magic links and OTP. Configure Redis if `_request_org_domain` and `_verify_org_domain` can land on different nodes. | --- ## Per-Org SAML 2.0 SSO ## Per-Organization SAML 2.0 SSO (Service Provider) For [organizations](./organizations) whose IdP speaks [SAML 2.0](https://www.oasis-open.org/standard/saml/) (Okta, Microsoft Entra ID, ADFS, …), Authorizer acts as a **SAML Service Provider (SP)** per org. Users authenticate at the corporate IdP; Authorizer validates the signed assertion, JIT-provisions the user, and issues a normal Authorizer session. ### Endpoints (per org) | Endpoint | Method | Purpose | |----------|--------|---------| | `/oauth/saml/{org_slug}/metadata` | GET | SP metadata XML — import this at the IdP | | `/oauth/saml/{org_slug}/login` | GET | Start an SP-initiated login (sends the AuthnRequest via HTTP-Redirect) | | `/oauth/saml/{org_slug}/acs` | POST | Assertion Consumer Service — the IdP posts the SAML response here | ### Setup All the admin ops below accept a super-admin, or that org's `authorizer:org_admin` member — see [Org-scoped admin](./organizations#org-scoped-admin). #### 1. Collect the IdP's details From the org's IdP you need: the **entity ID** (the assertion `Issuer`), the **SSO URL** (HTTP-Redirect binding), and the **X.509 signing certificate** (PEM). #### 2. Create the connection (admin API) ```graphql mutation { _create_org_saml_connection( params: { org_id: "ORG_ID" name: "Acme ADFS" idp_entity_id: "http://adfs.acme.com/adfs/services/trust" idp_sso_url: "https://adfs.acme.com/adfs/ls/" idp_certificate: "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----" # sp_entity_id / acs_url: optional overrides; derived from the request # host when omitted: # sp_entity_id → https://{host}/oauth/saml/{org_slug}/metadata # acs_url → https://{host}/oauth/saml/{org_slug}/acs # attribute_mapping: optional JSON, e.g. # "{\"email\":\"email\",\"given_name\":\"firstName\"}" # allow_idp_initiated: defaults to false (SP-initiated only) } ) { id org_id idp_entity_id sp_entity_id acs_url is_active } } ``` Related operations: `_update_org_saml_connection` (supplying `idp_certificate` replaces it; omitting leaves it intact), `_delete_org_saml_connection`, `_org_saml_connection` (fetch by `id` **or** `org_id`). The IdP certificate is accepted on write but never projected back. The `idp_entity_id` is globally unique across all trusted issuers — a SAML IdP cannot shadow an OIDC or client-assertion issuer registered at the same value. #### 3. Register the SP at the IdP Import the SP metadata from `/oauth/saml/{org_slug}/metadata`, or configure manually with the `sp_entity_id` (Audience) and `acs_url` (Recipient/Destination) shown in the connection. #### 4. Start a login from your app ``` GET https://your-authorizer.example/oauth/saml/{org_slug}/login ?redirect_uri=https://app.example.com/dashboard &state=RANDOM_STATE ``` `redirect_uri` is required and validated against `--allowed-origins`. On success Authorizer sets its session cookie and redirects back to `redirect_uri` with `state` — identical app-side behavior to the [OIDC broker](./org-sso-oidc). ### Attribute mapping & JIT provisioning The **NameID is always the federated subject**; federated identity is keyed by `(org_id, IdP entity ID, NameID)` — never by email, so an email collision with an existing account is rejected fail-closed rather than linked. First-time users are created and added as org members automatically. Profile attributes are extracted using the connection's `attribute_mapping` (Authorizer field → SAML attribute name). Defaults: | Authorizer field | Default SAML attribute | |------------------|------------------------| | `email` | `email` | | `given_name` | `firstName` | | `family_name` | `lastName` | | `nickname` | `displayName` | | `picture` | `picture` | ### Security model Enforced at the ACS (via the vetted `crewjam/saml` library plus explicit checks): - **Signature over the consumed assertion** — the XML-DSIG is validated on the same `` element that is consumed (or a Response signature covering it), defeating XML Signature Wrapping (XSW). Signatures validate **only** against the org's pinned IdP certificate. - **Unsigned assertions are rejected.** - **Audience / Recipient / Destination** must match this org's SP entity ID and ACS URL — an assertion minted for Org B cannot be consumed at Org A. - **`NotBefore` / `NotOnOrAfter`** validated with bounded clock skew. - **Single-use AssertionID** — consumed assertion IDs are cached until expiry; replays are rejected. - **InResponseTo** — SP-initiated responses must match a pending AuthnRequest; `RelayState` is an opaque single-use handle, never trusted as a redirect URL. The final app redirect is validated against `--allowed-origins`. - ACS successes and failures are audited; internal errors are never echoed to the caller. #### IdP-initiated SSO Disabled by default. Set `allow_idp_initiated: true` only if the org's IdP cannot do SP-initiated flows: enabling it disables InResponseTo validation for **all** responses on that connection (a library limitation), leaving replay defense solely to the single-use AssertionID cache. #### AuthnRequest signing AuthnRequests are currently emitted unsigned (HTTP-Redirect binding). All SP-side assertion security is enforced at the ACS; request signing protects the IdP against forged requests and is a future upgrade. ### Acting as an IdP instead? This page covers Authorizer as the **SP** (consuming assertions from an org's upstream corporate IdP). Authorizer can also act as a **SAML IdP** — issuing signed assertions to downstream Service Providers like Zendesk or Salesforce, per org. See [SAML 2.0 Identity Provider](./saml-idp). --- ## Per-Org OIDC SSO ## Per-Organization OIDC SSO (Broker) Each [organization](./organizations) can bring its own upstream OIDC identity provider (Okta, Microsoft Entra ID, Google Workspace, …). Authorizer acts as the **Relying Party (broker)**: the org's users authenticate at their corporate IdP, and Authorizer JIT-provisions them and issues a normal Authorizer session — your apps keep integrating with Authorizer only. ```mermaid sequenceDiagram participant U as User participant A as Authorizer participant I as Upstream IdP U->>A: GET /oauth/sso/{org_slug}/login A->>I: /authorize (PKCE + state + nonce) I-->>A: GET /oauth/sso/{org_slug}/callback (code) A->>A: verify ID token (JWKS, iss, aud, nonce) A->>A: JIT provision + session cookie A-->>U: redirect to your app (redirect_uri + state) ``` ### Setup All the admin ops below accept a super-admin, or that org's `authorizer:org_admin` member — see [Org-scoped admin](./organizations#org-scoped-admin). #### 1. Register Authorizer at the upstream IdP Create an OIDC app (authorization code flow) at the org's IdP with the redirect URI: ``` https://your-authorizer.example/oauth/sso/{org_slug}/callback ``` Note the issuer URL, client ID, and client secret the IdP gives you. #### 2. Create the connection (admin API) ```graphql mutation { _create_org_oidc_connection( params: { org_id: "ORG_ID" name: "Acme Okta" issuer_url: "https://acme.okta.com" # upstream OIDC discovery base client_id: "UPSTREAM_CLIENT_ID" # issued BY the IdP TO Authorizer client_secret: "UPSTREAM_SECRET" # stored encrypted, never returned # scopes: defaults to "openid profile email" when omitted # redirect_uri: derived from the request host when omitted } ) { id org_id issuer_url sso_client_id is_active } } ``` One OIDC connection per org. Related operations: | Operation | Purpose | |-----------|---------| | `_update_org_oidc_connection` | Update fields; supplying `client_secret` rotates it, omitting leaves it intact | | `_delete_org_oidc_connection` | Remove the connection | | `_org_oidc_connection` | Fetch by connection `id` **or** by `org_id` (supply exactly one) | The upstream `client_secret` is never projected back in any response. #### 3. Start a login from your app Send the org's users to: ``` GET https://your-authorizer.example/oauth/sso/{org_slug}/login ?redirect_uri=https://app.example.com/dashboard &state=RANDOM_STATE ``` - `redirect_uri` is **required** and must pass the instance's `--allowed-origins` validation. - `state` is optional and echoed back to your app. On success, Authorizer sets its session cookie and redirects the browser to your `redirect_uri` with `state` appended. From there, your app uses the normal Authorizer session (GraphQL `session` query, or silent OIDC via `/authorize`). The resulting tokens carry `login_method: "sso"`. ### JIT provisioning First-time users are created automatically: - Federated identity is keyed by **`(org_id, issuer, sub)`** — never by email. An upstream assertion whose email merely collides with an existing account is **rejected fail-closed**, not linked (account-takeover defense). - The user is added as a member of the organization. - Subsequent logins match the same federated identity and reuse the account. ### Security model Verified in the broker implementation: - **PKCE (S256)**, unguessable single-use `state`, and `nonce` on every upstream round trip. - **Mix-up defense** (RFC 9207): the returned ID token's `iss` must equal the issuer the dispatching connection discovered; an `iss` query parameter, when present, must match too. - ID token verified against the upstream **JWKS**; `aud` must equal the connection's upstream client ID; asymmetric algorithms only (`RS*/PS*/ES*` — `alg:none` and `HS*` are rejected). - All upstream fetches (discovery, JWKS, token exchange) use an SSRF-hardened HTTP client — host-pinned, redirects refused, response size capped. - SSO callbacks are audited (success and failure). ### SAML instead? If the org's IdP only speaks [SAML 2.0](https://www.oasis-open.org/standard/saml/), use the [per-org SAML SP](./org-saml) — same org model, same JIT provisioning. --- ## Organizations Organizations model tenants (customer companies, teams, business units) inside one Authorizer instance. Each organization has: - A unique, URL-safe **slug** (`name`) — it appears in per-org SSO URLs like `/oauth/sso/{org_slug}/login`. - An optional `display_name`. - An `enabled` flag — a disabled org's SSO and provisioning stop working. - **Members**: users linked to the org, each with a set of per-organization roles (independent of the user's global roles and of their roles in other orgs). Organizations are the anchor for the other enterprise features: | Feature | Attached per org | |---------|------------------| | [OIDC SSO broker](./org-sso-oidc) | One upstream OIDC IdP connection | | [SAML 2.0 SP](./org-saml) | One upstream SAML IdP connection | | [SCIM 2.0 provisioning](./scim) | One inbound SCIM endpoint + bearer token | | [Verified domains + Home Realm Discovery](./org-domains) | Many verified email domains, used to route logins to this org's SSO | Users who sign in through an org's SSO connection are JIT-provisioned and automatically added as members of that organization. ### Admin API Organization create/update/delete/list stay super-admin-only (`x-authorizer-admin-secret` header or the `authorizer.admin` cookie) — only the platform operator provisions/deprovisions tenants. Fetching a single org and all member-management ops are **org-scoped-admin gated**: super-admin, or that org's `authorizer:org_admin` member (see [Org-scoped admin](#org-scoped-admin) below). | Operation | Type | Purpose | Who can call | |-----------|------|---------|---------------| | `_create_organization` | mutation | Create an org (`name` slug must be unique and URL-safe) | Super-admin only | | `_update_organization` | mutation | Update `name`, `display_name`, `enabled` | Super-admin only | | `_delete_organization` | mutation | Delete the org | Super-admin only | | `_organization` | query | Fetch one org by `id` | Super-admin or that org's `authorizer:org_admin` | | `_organizations` | query | Paginated list of all orgs | Super-admin only | | `_add_org_member` | mutation | Add a user as member with optional per-org roles | Super-admin or that org's `authorizer:org_admin` | | `_remove_org_member` | mutation | Remove a member | Super-admin or that org's `authorizer:org_admin` | | `_org_members` | query | Paginated member list for an org | Super-admin or that org's `authorizer:org_admin` | | `_user_organizations` | query | Paginated list of the orgs a user belongs to, with their roles in each | Super-admin or that org's `authorizer:org_admin` | #### Create an organization ```graphql mutation { _create_organization( params: { name: "acme", display_name: "Acme Corp" } ) { id name display_name enabled } } ``` #### Manage members ```graphql mutation { _add_org_member( params: { org_id: "ORG_ID" user_id: "USER_ID" roles: ["admin"] # per-org roles; defaults to empty when omitted } ) { id org_id user_id roles } } ``` ```graphql query { _org_members(params: { org_id: "ORG_ID" }) { pagination { total } org_members { user_id roles created_at email given_name family_name } } } ``` **Organization member fields** | Field | Type | Description | | ------------ | -------- | ----------- | | `user_id` | `string` | The user's unique identifier | | `roles` | `[string]` | Per-organization roles assigned to this member | | `created_at` | `string` | Timestamp when the membership was created | | `email` | `string` | User's email (may be empty if the user no longer exists) | | `given_name` | `string` | User's first name (may be empty if the user no longer exists) | | `family_name` | `string` | User's last name (may be empty if the user no longer exists) | ```graphql mutation { _remove_org_member(params: { org_id: "ORG_ID", user_id: "USER_ID" }) { message } } ``` Notes: - Membership is unique per `(org_id, user_id)` — adding the same user twice is rejected. - Per-org roles are independent across orgs: the same user can be `admin` in one org and `viewer` in another. These are your app's own roles — not to be confused with the reserved `authorizer:org_admin` role below. - SSO JIT provisioning and SCIM provisioning create memberships automatically; `_add_org_member` is for manual/back-office management. ### Org-scoped admin A member holding the reserved, namespaced role **`authorizer:org_admin`** can self-manage that one org's SSO/SCIM/domain settings — [SAML](./org-saml), [OIDC](./org-sso-oidc), [SCIM](./scim), and [verified domains](./org-domains) — without the platform super-admin secret. Every gated operation passes when the caller is either a platform super-admin, or an authenticated member whose `OrgMembership` for that org includes this exact role string. It is intentionally namespaced (not the bare `admin`) so it can never collide with your app's own per-org roles — granting a member `roles: ["admin"]` for your app's own purposes does **not** give them org-scoped admin rights. Grant it like any other per-org role, via `_add_org_member` (or by adding it to an existing member's `roles`): ```graphql mutation { _add_org_member( params: { org_id: "ORG_ID" user_id: "USER_ID" roles: ["authorizer:org_admin"] } ) { id org_id user_id roles } } ``` Scope of what this grants: - **Org create, update, delete, and the all-orgs list (`_organizations`) remain super-admin-only** — an org-admin can never provision/deprovision tenants or see other orgs. - An org-admin can manage members of **their own org only** (including granting `authorizer:org_admin` to another member of that org) — never another org's membership. - A non-super-admin caller cannot remove an org's last `authorizer:org_admin` member, so an org can't accidentally lock itself out of self-service (a super-admin can always recover it). - Bootstrapping an org's first `authorizer:org_admin` still requires a super-admin, via `_create_organization` followed by `_add_org_member`. --- ## SAML 2.0 Identity Provider ## SAML 2.0 Identity Provider (IdP) Per [organization](./organizations), Authorizer can also act as a **[SAML 2.0](https://www.oasis-open.org/standard/saml/) Identity Provider** — issuing signed assertions to downstream Service Providers (Zendesk, Salesforce, Notion, …) so their SAML-based SSO logs users in with their existing Authorizer session. This is the architectural inverse of [Authorizer as SAML SP](./org-saml): there Authorizer *consumes* an assertion from a corporate IdP; here it *produces* one for a downstream SP. Do not confuse the two — a `SAMLServiceProvider` row (this page) and an `OrgSAMLConnection` row (the SP-role doc) are unrelated tables. ```mermaid flowchart LR subgraph SP["Per-org SP role (org-saml.md)"] direction LR Okta -- assertion --> Auth1["Authorizer (= SP)"] end subgraph IDP["Per-org IdP role (this page)"] direction LR Auth2["Authorizer (= IdP)"] -- assertion --> Zendesk end ``` ### Endpoints (per org) | Endpoint | Method | Purpose | |----------|--------|---------| | `/saml/idp/{org_slug}/metadata` | GET | IdP metadata XML — import this at the downstream SP | | `/saml/idp/{org_slug}/sso` | GET, POST | SP-initiated SSO — receives the SP's `AuthnRequest` (HTTP-Redirect or HTTP-POST binding) | | `/saml/idp/{org_slug}/sso/{sp_id}` | GET | IdP-initiated SSO — unsolicited assertion POSTed to the SP identified by `sp_id`, gated by that SP's `allow_idp_initiated` flag | All three resolve the org by `org_slug`; an SP registered for one org is never reachable through another org's endpoints. ### Registering a downstream SP Admin operations (super-admin or org-admin of `org_id`), available via GraphQL, gRPC (`AuthorizerAdminService`), and the dashboard (**Organization → SAML Service Providers**): | GraphQL operation | Type | gRPC / REST-gateway | Purpose | |--------------------|------|----------------------|---------| | `_create_saml_service_provider` | mutation | `CreateSamlServiceProvider` · `POST /v1/admin/create_saml_service_provider` | Register a downstream SP | | `_update_saml_service_provider` | mutation | `UpdateSamlServiceProvider` · `POST /v1/admin/update_saml_service_provider` | Update name, `entity_id`, `acs_url`, cert, attribute mapping, `allow_idp_initiated`, `is_active` | | `_delete_saml_service_provider` | mutation | `DeleteSamlServiceProvider` · `POST /v1/admin/delete_saml_service_provider` | Remove a registered SP | | `_saml_service_provider` | query | `GetSamlServiceProvider` · `POST /v1/admin/saml_service_provider` | Fetch one SP by `id` | | `_list_saml_service_providers` | query | `ListSamlServiceProviders` · `POST /v1/admin/saml_service_providers` | Paginated list for an org | | `_import_saml_sp_metadata` | mutation | `ImportSamlSpMetadata` · `POST /v1/admin/import_saml_sp_metadata` | Parse pasted SP metadata XML into `entity_id` / `acs_url` / certificate (does **not** create a record — prefill only; super-admin only, no remote fetch) | ```graphql mutation { _create_saml_service_provider( params: { org_id: "ORG_ID" name: "Zendesk prod" entity_id: "https://acme.zendesk.com/sso/saml" acs_url: "https://acme.zendesk.com/access/saml" # sp_cert_pem: optional SP signing certificate (PEM) # name_id_format: defaults to urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress # mapped_attributes: optional JSON, e.g. # "{\"email\":\"email\",\"given_name\":\"firstName\",\"groups\":\"memberOf\"}" # allow_idp_initiated: defaults to false (SP-initiated only) } ) { id entity_id acs_url allow_idp_initiated is_active } } ``` `entity_id` is unique within the org — `(org_id, entity_id)` is the lookup that resolves an incoming `AuthnRequest` to this record, and it also fixes the assertion's `Audience`. `acs_url` is the **only** place an assertion is ever POSTed; a request-supplied ACS URL that doesn't match this value is rejected. ### Attribute mapping `mapped_attributes` is JSON mapping Authorizer profile fields to the SAML attribute **names** this SP expects — the inverse of the SP-role's `attribute_mapping`. Defaults when omitted: | Authorizer field | Default SAML attribute | |------------------|------------------------| | `email` | `email` (only ever emitted once the user's email is verified) | | `given_name` | `given_name` | | `family_name` | `family_name` | | `nickname` | `nickname` | | `picture` | `picture` | #### Group assertion (SCIM groups → SAML `groups`) If the user belongs to [SCIM groups](./scim) in the issuing org, their group display names are emitted as one multi-valued attribute (default name `groups`, or a `groups` key in `mapped_attributes`). This is gated to the issuing org's namespace only — a group from a different org the user also belongs to can never appear in the assertion. See the [SCIM doc](./scim) for how groups and memberships are managed; this page only covers the SAML projection. ### Signing key rotation Each org gets its own RSA signing keypair (`SAMLIDPKey`), generated lazily on first use — independent of the JWT signing key, since XML-DSIG needs the X.509 certificate wrapper. A key's `status` is one of: | Status | Meaning | |--------|---------| | `current` | The single key new assertions are signed with. At most one per org. | | `active` | A formerly-current key, still published in IdP metadata so SPs with cached metadata keep validating during the rotation overlap. Never signs. | | `retired` | Explicitly retired by an admin — no longer published, no longer usable. Retirement is always an explicit action, never time-based. | Admin operations: | GraphQL operation | Type | Purpose | |--------------------|------|---------| | `_rotate_saml_idp_cert` | mutation | Generate a new keypair as `current`; the previous `current` key is demoted to `active` | | `_retire_saml_idp_key` | mutation | Retire an `active` key (an org's `current` key cannot be retired — rotate first) | | `_list_saml_idp_keys` | query | List an org's keys with their `status` (private key is never projected) | ```graphql mutation { _rotate_saml_idp_cert(params: { org_id: "ORG_ID" }) { id status algorithm } } ``` Recommended rotation workflow: call `_rotate_saml_idp_cert`, wait for downstream SPs to refresh their cached copy of `/saml/idp/{org_slug}/metadata` (both certs are published during the overlap), then call `_retire_saml_idp_key` on the old key once you've confirmed nothing still needs it. ### Security model | Invariant | Enforcement | |-----------|-------------| | ACS/EntityID strict binding | The SP is resolved from the registered `SAMLServiceProvider` row by the `AuthnRequest` issuer; the ACS URL is taken **only** from that row, never from the request — closes the open-redirect / assertion-exfiltration path. An unregistered SP is refused. | | Audience isolation | The assertion `Audience` is set to the resolved SP's `entity_id`, so an assertion minted for SP-A can never validate at SP-B. | | Org-membership gating | The authenticated user must be a member of the org the assertion is minted for. Without this, any logged-in Authorizer user could hit another org's `/saml/idp/{org}/sso` and get an assertion signed by that org's key. Absent-or-errored membership is treated as denied (fail-closed), never silently allowed. | | Verified-email gating | When the Subject `NameID` (or the `email` attribute) would be the user's email address, that email must be verified — otherwise a member could register `victim@org.com` and be asserted as the victim to an SP that keys off email. | | IdP-initiated gating | Unsolicited (IdP-initiated) SSO is refused unless the SP's `allow_idp_initiated` is `true`. Default is `false` (SP-initiated only). | | RelayState bound | IdP-initiated `RelayState` is capped at 2048 bytes and dropped (not rejected) above that — it is only ever reflected into the delivered response form, never treated as a redirect target. | | Signing scope | Signing uses only the org's `current` key; metadata additionally publishes `active` certs so a rotation overlap doesn't break SPs with cached metadata. | | No unauthenticated issuance | SP-initiated flows only produce an assertion once the browser presents a valid Authorizer session; otherwise the request bounces through the normal login UI and resumes via an opaque, single-use continuation token — never a request-supplied redirect. | #### IdP-initiated SSO `GET /saml/idp/{org_slug}/sso/{sp_id}` POSTs an unsolicited assertion straight to the SP's ACS — there's no `AuthnRequest` to bind an `InResponseTo` to, so replay defense for this path is the **consuming SP's** job (single-use `AssertionID`); Authorizer bounds exposure with a tight `NotBefore`/`NotOnOrAfter` window. Only enable `allow_idp_initiated` for SPs that support unsolicited assertions. --- ## SCIM 2.0 Provisioning Authorizer exposes a per-[organization](./organizations) inbound **[SCIM 2.0](https://datatracker.ietf.org/doc/html/rfc7644)** ([RFC 7644](https://datatracker.ietf.org/doc/html/rfc7644)) endpoint so enterprise directories (Okta, Microsoft Entra ID, OneLogin, …) can provision and deprovision that org's users automatically. - Base URL: `https://your-authorizer.example/scim/v2` - Authentication: `Authorization: Bearer ` — one token per org - Media type: `application/scim+json`; errors use the SCIM error schema The organization is resolved **solely from the bearer token** — never from the URL or request body — so one org's token can never touch another org's users. A missing, malformed, or wrong token is a constant-time `401`. ### Create the endpoint (admin API) All the ops below accept a super-admin, or that org's `authorizer:org_admin` member — see [Org-scoped admin](./organizations#org-scoped-admin). One SCIM endpoint per org, keyed by `org_id`: ```graphql mutation { _create_scim_endpoint(params: { org_id: "ORG_ID" }) { scim_endpoint { id org_id enabled } token # the bearer credential — shown ONCE, store it now } } ``` The token is high-entropy and stored only as a hash; like client secrets, it is returned **once** at creation and once at rotation, never again. | Operation | Type | Purpose | |-----------|------|---------| | `_create_scim_endpoint` | mutation | Create the org's endpoint; returns the token once | | `_rotate_scim_token` | mutation | Invalidate the old token, return a new one once | | `_delete_scim_endpoint` | mutation | Remove the endpoint | | `_scim_endpoint` | query | Fetch the endpoint record (never the token) | All keyed by `org_id`. ### Supported SCIM surface | Route | Method | Behavior | |-------|--------|----------| | `/scim/v2/Users` | POST | Create (JIT-provision) a user in the org | | `/scim/v2/Users` | GET | Single-term filter over `userName`, `emails.value`, `name.givenName`, `name.familyName`, `active`, `externalId` (see [Filter operators](#filter-operators)), with `startIndex`/`count` pagination. An unfiltered list returns an empty set — full org enumeration is out of scope | | `/scim/v2/Users/{id}` | GET | Fetch one user | | `/scim/v2/Users/{id}` | PUT | Replace mutable profile fields + `active` flag | | `/scim/v2/Users/{id}` | PATCH | Partial update — see [User PATCH](#user-patch) for the supported attributes | | `/scim/v2/Users/{id}` | DELETE | Treated as deactivation (`active: false`) | | `/scim/v2/Groups` | POST | Create a group in the org (see [Group provisioning](#group-provisioning)) | | `/scim/v2/Groups` | GET | Only the `displayName eq "..."` filter (case-insensitive). An unfiltered list, or any other operator, is unsupported | | `/scim/v2/Groups/{id}` | GET | Fetch one group, with resolved `members` | | `/scim/v2/Groups/{id}` | PUT | Replace `displayName` and set membership to exactly the posted `members` | | `/scim/v2/Groups/{id}` | PATCH | Partial update to `displayName`/`externalId` plus member add/remove/replace | | `/scim/v2/Groups/{id}` | DELETE | Remove the group and its FGA membership tuples | | `/scim/v2/ServiceProviderConfig`, `/ResourceTypes`, `/Schemas` | GET | SCIM discovery documents | Notes: - `userName` is required on create; if the IdP omits it, the primary email is used as `userName`. - `externalId` is stored and round-tripped, so the IdP can correlate its own IDs. - Group operations return `501` (`group provisioning is not enabled on this server`) if the org has no [FGA](../core/fga-guide) authorization engine configured — group membership is stored as FGA tuples, not a database column. ### Filter operators `GET` list filters are single-term only — compound filters (`and`/`or`/`not`), value-path filters (`emails[type eq "work"]`), and ordering operators (`gt`/`lt`/…) are not supported and return `400 invalidFilter`, never a silent empty `200` (a connector reads an empty `200` as "does not exist" and duplicates the create). | Resource | Attributes | Operators | |----------|-----------|-----------| | `/scim/v2/Users` | `userName`, `emails.value`, `name.givenName`, `name.familyName`, `active`, `externalId` | `eq`, `ne`, `co`, `sw`, `pr` (`co`/`sw` rejected on `active` — meaningless on a boolean) | | `/scim/v2/Groups` | `displayName` | `eq` only | Notes: - `eq` on `userName`/`emails.value`/`externalId` (Users) and `displayName` (Groups) is an indexed lookup — the dedup probe an IdP sends before every create. Every other operator/attribute combination falls back to a bounded in-app scan of the org's members (capped at 1,000 scanned memberships, paged 100 at a time) so a very large org can't turn a filter into unbounded work. - String comparisons are case-insensitive, matching SCIM's default `caseExact:false` for these attributes. - `startIndex`/`count` (RFC 7644 §3.4.2.4) paginate the Users list response; Groups list only ever returns 0 or 1 resource (the `displayName eq` match), so pagination params are not applicable there. ### User PATCH {#user-patch} `PATCH /scim/v2/Users/{id}` supports `add`/`replace` operations (treated identically for these single-valued attributes) on: | Path | Effect | |------|--------| | `active` | Deactivate/reactivate — see [Deprovisioning semantics](#deprovisioning-semantics) | | `name.givenName`, `name.familyName` | Update the profile name | | `userName`, `emails` / `emails[type eq "..."].value` | Update the user's email (uniqueness-checked — `409` if another user already holds it). Refused for a user shared with another organization — see [Shared users](#shared-users) | | `phoneNumber`, `phoneNumbers` / `phoneNumbers[...].value` | Update the phone number (uniqueness-checked). Refused for a user shared with another organization — see [Shared users](#shared-users) | | `externalId` | Update the correlation id | Both the path-qualified shape (`{"op":"replace","path":"active","value":false}`) and the no-path attribute-map shape (`{"op":"replace","value":{"active":false,"name":{"givenName":"Jonathan"}}}`) are accepted, since Okta and Entra don't send the same one. `remove` ops and any path this server doesn't model (e.g. enterprise-extension attributes like `manager`/`department`) are silently skipped rather than rejected, so a connector that also syncs unsupported attributes doesn't fail the whole request. A patch that changes nothing returns the resource unchanged and fires no webhook. #### Shared users {#shared-users} A user's email and phone number are global to the account. They are what the user signs in with and where password-reset and OTP messages go, in every organization. So when a user is a member of **any other organization** (active or deprovisioned), a SCIM `PATCH` that would change their email or phone is rejected: ```json { "schemas": ["urn:ietf:params:scim:api:messages:2.0:Error"], "status": "400", "scimType": "mutability", "detail": "email and phone of a user shared with another organization cannot be changed" } ``` The whole request is rejected, so no other attribute in it is applied either. Sending the user's current email again, including with different letter case, is not a change and still succeeds, so routine IdP re-syncs keep working. Users who belong only to this organization are unaffected. To change a shared user's email or phone, have the user change it themselves, or change it through the [admin API](../core/graphql-api). :::caution Changed in v2.4.8 Before v2.4.8 one organization's SCIM token could change a shared user's email or phone, and so redirect password resets for an account another organization also relies on ([GHSA-p7g3-2258-8wmp](https://github.com/authorizerdev/authorizer/security/advisories/GHSA-p7g3-2258-8wmp)). If an IdP connector now logs `400 mutability` for a user, that user is a member of more than one organization. ::: ### Deprovisioning semantics Deactivation is the enterprise-offboarding path and is **synchronous**: - `PATCH {"active": false}` (or `DELETE`) marks the user revoked and **immediately revokes their sessions and refresh tokens** — a still-held access token fails introspection and cannot be refreshed. - A user provisioned with `active: false` is deprovisioned from birth (no token can ever be issued). - `active: true` reactivates the account. ### Example: provision a user ```bash curl -s -X POST https://your-authorizer.example/scim/v2/Users \ -H "Authorization: Bearer $SCIM_TOKEN" \ -H "Content-Type: application/scim+json" \ -d '{ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"], "userName": "jane@acme.com", "externalId": "00u1abcd", "name": { "givenName": "Jane", "familyName": "Doe" }, "emails": [{ "value": "jane@acme.com", "primary": true }], "active": true }' ``` Dedup probe (what Okta/Entra send before creating): ```bash curl -s -G https://your-authorizer.example/scim/v2/Users \ -H "Authorization: Bearer $SCIM_TOKEN" \ --data-urlencode 'filter=userName eq "jane@acme.com"' ``` ### Group provisioning SCIM Groups ([RFC 7643](https://datatracker.ietf.org/doc/html/rfc7643) §4.2) provision org-scoped groups whose membership drives both authorization and SAML assertions. A group carries only identity/metadata (`displayName`, `externalId`, timestamps) — membership is **not** a database column. It's modelled as [FGA](../core/fga-guide) relationship tuples (`group:/#member@user:`), the same graph that resolves roles and nested groups, so the group→role grant and the SAML group projection are both just reads of that one graph. - **Cross-org isolation (H6)**: a group is only visible/mutable through the SCIM connection whose org it belongs to; a cross-org group id resolves to `404`, indistinguishable from a nonexistent one. - **`displayName` uniqueness** is enforced per-org at the service layer (not a DB constraint, for identical behavior across every storage backend) — a create that collides on `displayName` with no matching `externalId` gets `409 uniqueness`. - **`displayName` matching is case-insensitive** (SCIM `caseExact:false`, RFC 7644 §3.4.2.2): filtering for `displayname eq "engineers"` finds a group stored as `"Engineers"`, and returns it with its stored casing. - **`externalId` correlation**: a create carrying an `externalId` that already identifies a group in the org is idempotent — it adopts a `displayName` rename and syncs members (`200`) instead of creating a duplicate (`201`). - **Pagination / safety valve**: the `displayName` lookup scans the org's groups (paged internally, not a single unbounded query) up to a **100,000-group safety valve** per org — a circuit-breaker against pathological orgs, not a realistic ceiling on group count. Reading a group's `members` similarly pages through the underlying FGA tuples 100 at a time. - **Deleting a group** removes its row and every membership tuple pointing at it; role→group bindings (`role:.../r#assignee@group:.../g#member`) are left for an admin to clean up via `_fga_delete_tuples` if desired — group ids are UUIDs and never reused, so a dangling binding simply resolves to nobody. #### PATCH operations on Groups `PATCH /scim/v2/Groups/{id}` supports: | Path | Op | Effect | |------|----|--------| | `displayName` | `add`/`replace` | Rename (uniqueness-checked) | | `externalId` | `add`/`replace` | Update the correlation id | | `members` (or `members[value eq "..."]`) | `add` | Add the listed users to the group | | `members` (or `members[value eq "..."]`) | `remove` | Remove the listed users | | `members` | `remove`, no member list | **Clear every member** (the unfiltered "empty this group" shape IdPs send when deprovisioning a group) | | `members` | `replace` | Set membership to exactly the posted list (an empty list clears every member) | Both the RFC/Okta filtered-path shape (`{"op":"remove","path":"members[value eq \"\"]"}`) and Entra's non-RFC shape (`{"op":"remove","path":"members","value":[{"value":""}]}`) are accepted, along with the no-path attribute-map shape. Every added member must already be an org member — a user id from outside the org is silently skipped, never written as a tuple. A `PATCH` op targeting an unsupported path (e.g. `emails`, `name.givenName`) returns `400 invalidPath`, never a silent no-op `200`. #### Role and SAML projection Group membership isn't read directly by clients — it's projected into two places at session-issuance time: - **[OpenFGA](https://openfga.dev) roles**: a role granted to a group (`role:/#assignee@group:/#member`) is resolved transitively for every member and unioned onto the roles already minted into that org's session/JWT — see the [FGA guide](../core/fga-guide) for the tuple model (in particular [groups as subjects](../core/fga-guide#groups-as-subjects)). This only ever *adds* roles; a lookup failure derives none rather than blocking login. - **SAML group assertions**: when Authorizer acts as an [IdP](./saml-idp), a user's groups *in the org the assertion is being issued for* are resolved and emitted as a multi-valued attribute (`groups` by default) — see [Group assertion](./saml-idp#group-assertion-scim-groups--saml-groups). Both projections are org-namespaced and fail closed: a user who belongs to groups/roles in other orgs never leaks them into a token or assertion issued for this org, and any FGA lookup error yields nothing rather than a partial or wrongly-scoped set. #### Example: create and patch a group ```bash curl -s -X POST https://your-authorizer.example/scim/v2/Groups \ -H "Authorization: Bearer $SCIM_TOKEN" \ -H "Content-Type: application/scim+json" \ -d '{ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"], "displayName": "Engineers", "externalId": "grp-eng", "members": [{ "value": "" }] }' ``` ```bash curl -s -X PATCH https://your-authorizer.example/scim/v2/Groups/ \ -H "Authorization: Bearer $SCIM_TOKEN" \ -H "Content-Type: application/scim+json" \ -d '{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [ { "op": "add", "path": "members", "value": [{ "value": "" }] } ] }' ``` ### Provisioning webhooks Every SCIM lifecycle event fires an [event webhook](../core/graphql-api#webhooks) (configured via `_add_webhook`, keyed to one of the event names below), so a customer's own audit/automation pipeline can react to IdP-driven changes without polling: | Event | Fires when | |-------|-----------| | `user.provisioned` | An IdP creates a user via SCIM | | `user.deprovisioned` | An IdP deactivates a user (`active:false` PATCH/PUT, or `DELETE`) | | `user.scim_updated` | An IdP changes a user's attributes via SCIM (name/email/phone/externalId, or reactivation) | | `group.created` | An IdP creates a group via SCIM | | `group.updated` | An IdP changes a group's `displayName`/`externalId` or membership | | `group.deleted` | An IdP deletes a group via SCIM | Delivery is **asynchronous** — fired off the request path after the SCIM operation commits, so a slow or unreachable webhook endpoint never delays or fails the IdP's HTTP response. Delivery is best-effort per webhook (one bad endpoint doesn't block the others) and logged. Payload shape: - User events: `{ "webhook_id", "event_name", "event_description", "user": { ...full user object... } }` - Group events: `{ "webhook_id", "event_name", "event_description", "group": { "id", "org_id", "display_name", "external_id" } }` — note the key is `group`, not `user`, and it carries only identity fields (no members list); `external_id` is de-namespaced back to the raw IdP value. Every delivery carries an `X-Authorizer-Signature` header (HMAC-SHA256 over the raw JSON body, keyed on the client secret) so the receiver can verify authenticity. ### IdP configuration pointers - **Okta** — add a SCIM 2.0 provisioning integration; set the SCIM connector base URL to `https://your-authorizer.example/scim/v2`, authentication mode *HTTP Header* with the bearer token, and enable Create/Update/Deactivate users. - **Microsoft Entra ID (Azure AD)** — in an enterprise application's *Provisioning* settings, set the Tenant URL to `https://your-authorizer.example/scim/v2` and the Secret Token to the endpoint token, then test the connection. Entra's deprovision flow (`PATCH active:false`) is fully supported and revokes sessions immediately. Rotate the token with `_rotate_scim_token` and update the IdP's secret whenever it may have been exposed. --- ## Token Exchange & Delegation ## Token Exchange & Delegation (RFC 8693) Authorizer implements [RFC 8693 OAuth 2.0 Token Exchange](https://www.rfc-editor.org/rfc/rfc8693) in a **delegation-only profile**: an agent (a `service_account` from the [client registry](../core/client-registry)) trades a user's token plus its own token for a short-lived, down-scoped, audience-bound token that carries *both* identities. Built for AI agents and service-to-service acting-on-behalf-of. Three guarantees on every downstream call: 1. **Both identities travel together** — the resource server sees *agent X acting for subject Y* (`sub` = the delegated subject, `act.sub` = agent). The subject is usually a user; in an agent-to-agent chain it is the delegated service account. 2. **Least privilege** — the token is attenuated to the intersection of what the user has, what the agent may ever have, and what was asked for. 3. **The chain is auditable** — `app → agent → user` is recorded in the audit log. ### The `act` claim ```jsonc { "iss": "https://your-authorizer.example", "sub": "user-alice-id", // whose authority is exercised "aud": "https://calendar.example", // the bound resource (RFC 8707) "scope": ["calendar:read"], // attenuated "exp": 1712500300, // now + 5 minutes "client_id": "agent-client-id", // RFC 9068: the calling agent "act": { // who is acting "sub": "agent-client-id", "act": { "sub": "app-client-id" } // nested: prior hop, if re-exchanged } } ``` `sub` stays the **delegated subject** — the user in the common app-acting-for-user case, or the delegated service account in an agent-to-agent chain, in which case the token also carries `login_method: service_account` so downstream authorization classifies it as a machine rather than a human (see [Multi-hop delegation](#multi-hop-delegation)); `act.sub` is the **immediate actor** — always the *authenticated* agent's registered `client_id`, never a token-supplied claim; nested `act` encodes multi-hop delegation. The JWT header carries `typ: at+jwt` (RFC 9068). `act` and `client_id` are reserved claims — the custom access token script cannot forge them (it is not run for delegated tokens at all). ### Request `POST /oauth/token` with the calling agent authenticated as a `service_account` (`client_secret_basic`, `client_secret_post`, or an [RFC 7523](https://datatracker.ietf.org/doc/html/rfc7523) [`client_assertion`](./workload-identity)): | Parameter | Required | Notes | |-----------|----------|-------| | `grant_type` | Yes | `urn:ietf:params:oauth:grant-type:token-exchange` | | `subject_token` | Yes | The user's Authorizer access token — the authority being exercised | | `subject_token_type` | Yes | `urn:ietf:params:oauth:token-type:access_token` or `urn:ietf:params:oauth:token-type:jwt` | | `actor_token` | Yes | The agent's own access token (from `client_credentials`). Omitting it is rejected — subject-only exchange is impersonation, which this endpoint does not serve | | `actor_token_type` | Yes | Same URNs as `subject_token_type` | | `resource` | Yes | **Exactly one** (RFC 8707). Zero or repeated values are rejected — a multi-audience delegated token would be replayable across resource servers | | `scope` | No | Requested down-scope (space-separated) | ```bash # 1. Agent gets its own token AGENT_TOKEN=$(curl -s -X POST $AUTHORIZER_URL/oauth/token \ -u "$AGENT_CLIENT_ID:$AGENT_CLIENT_SECRET" \ -d "grant_type=client_credentials" | jq -r .access_token) # 2. Exchange: user's token + agent's token → delegated token curl -s -X POST $AUTHORIZER_URL/oauth/token \ -u "$AGENT_CLIENT_ID:$AGENT_CLIENT_SECRET" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \ -d "subject_token=$USER_ACCESS_TOKEN" \ -d "subject_token_type=urn:ietf:params:oauth:token-type:access_token" \ -d "actor_token=$AGENT_TOKEN" \ -d "actor_token_type=urn:ietf:params:oauth:token-type:access_token" \ -d "resource=https://calendar.example" \ -d "scope=calendar:read" ``` **Response** ([RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) §2.2): ```json { "access_token": "eyJhbG...", "issued_token_type": "urn:ietf:params:oauth:token-type:access_token", "token_type": "Bearer", "expires_in": 300, "scope": "calendar:read" } ``` ### Scope attenuation The delegated token's scope is always: ``` effective = subject_token.scope ∩ agent.allowed_scopes ( ∩ requested scope, when given ) ``` - The agent's [`allowed_scopes`](../core/client-registry) is its **delegation ceiling** — it can never exceed it, even when the subject is an admin. An agent with an empty ceiling can delegate nothing (`invalid_scope`). - Because the subject token's own scope is always intersected, attenuation is **monotonic**: re-exchanging an already-narrowed delegated token can only narrow further — never restore scope. - An empty intersection is rejected with `invalid_scope`, never silently widened. ### Multi-hop delegation A delegated token can itself be the `subject_token` of a further exchange (app → agent → sub-agent). The prior `act` chain nests under the new actor. The chain depth is capped at **4**; deeper chains are rejected with `invalid_request`. The subject is carried unchanged through every hop, and so is its identity type. When the subject is a **service account** (agent → agent), each minted token carries `login_method: service_account` and resolves to `service_account:` for authorization — never to `user:`. :::note Changed in 2.4.1 Before 2.4.1 a machine-subject delegated token dropped `login_method`, so authorization misclassified the service account as a human user ([GHSA-vq29-8q3c-3hrm](https://github.com/authorizerdev/authorizer/security/advisories/GHSA-vq29-8q3c-3hrm)) — and, because the second hop then looked the service account up as a user and found nothing, an agent-to-agent chain never worked past its first hop. Both are fixed. Subject liveness is still re-checked at every hop, scope still attenuates monotonically, and the depth cap is unchanged. ::: A runnable 4-hop example (`orchestrator → research-agent → crm-reader → export-agent`, plus live rejections for a 5th hop, scope re-widening, and actor-token substitution) is in [`with-agent-delegation`](https://github.com/authorizerdev/examples/tree/main/with-agent-delegation). ### Resource binding & validation - `aud` on the delegated token is the single `resource` — it is only valid at that resource server. - Delegated tokens are **stateless at the resource server**: it validates them via local JWT verification against [`/.well-known/jwks.json`](../core/oauth2-oidc), checking `iss`, `aud`, `exp` and `scope`. - **`/oauth/introspect` cannot be used for a delegated token.** Introspection answers only for a token whose `aud` is the *authenticated caller's* `client_id`, and a delegated token's `aud` is the RFC 8707 resource URI — so a resource server presenting its own credentials always gets `{"active": false}`. That is correct per RFC 7662 §2.2 (it must not become an oracle), but it means introspection is useless as a revocation signal here: a resource server that treats `active: false` as "revoked" will reject every valid delegated token. - They are **not refreshable**. TTL is fixed at **5 minutes**; the agent re-exchanges when it needs more time. At the resource server the short TTL is the entire revocation story — revoking the user stops the *next* exchange immediately (see below), and in-flight tokens die within the window. - The token carries an opaque `sid` naming the session it was derived from. At **Authorizer's own API** that makes it as revocable as the credential that seeded it — logout, password reset and admin session wipes all stop it on the next call. A resource server verifying offline cannot see this; do not design one that assumes it can. To let an agent call **Authorizer itself** (e.g. to ask `check_permissions` about its own authority), exchange with `resource` set to your Authorizer URL. What happens then — the `perms(agent) ∩ perms(user)` intersection — is covered in [Agent Identity & Permissions](./agent-identity). ### Security invariants | Invariant | Enforcement | |-----------|-------------| | Delegation only — no impersonation | `actor_token` is mandatory; a subject-only exchange is rejected | | Actor is the authenticated caller | The `actor_token`'s `sub` must be the authenticated agent — a valid-but-unrelated token cannot stand in as the actor | | Actor identity is unforgeable | `act.sub` is stamped from the agent's registered `client_id`, never from a request or token claim | | Only Authorizer-issued tokens | Both tokens must verify against this server's signing key, with `iss` bound to this host and `token_type=access_token` | | Revoked users cannot seed delegation | A deactivated/revoked subject user (e.g. [SCIM](./scim) `active:false`) is rejected fail-closed; a user that cannot be loaded is also rejected (a DB error never fails open) | | Non-widening | Monotonic scope intersection (above) | | Bounded chains | `act` depth ≤ 4 | | Auditable | Every exchange logs actor, `on_behalf_of` (+ type `user`/`agent`), the serialized delegation chain (`app>agent>user`), and the bound resource in the audit log metadata | ### Errors | Error | Cause | |-------|-------| | `invalid_request` | Missing/unsupported token types, missing `actor_token`, `resource` count ≠ 1, chain too deep | | `invalid_grant` | Subject or actor token invalid/expired, actor token not the caller's, subject revoked or unverifiable | | `invalid_scope` | Empty agent ceiling, or empty intersection after attenuation | | `invalid_client` / `unauthorized_client` | Client authentication failed, or the caller is not a `service_account` | --- ## Workload Identity ## Workload Identity (Secretless Client Authentication) A [`service_account` client](../core/client-registry) normally authenticates with a stored `client_secret`. Workload identity removes the stored secret entirely: the workload authenticates at `POST /oauth/token` with a signed JWT it **already possesses** — a Kubernetes projected ServiceAccount token or a [SPIFFE](https://spiffe.io) JWT-SVID — presented as an [RFC 7523](https://www.rfc-editor.org/rfc/rfc7523) `client_assertion`. Nothing to distribute, rotate, or leak. The assertion works as client authentication on both machine grants: [`client_credentials`](../core/client-registry) and [token exchange](./token-exchange). ```mermaid sequenceDiagram participant W as Workload participant A as Authorizer Note over W: holds a platform-issued JWT (K8s SA token or SPIFFE JWT-SVID) W->>A: POST /oauth/token, grant_type=client_credentials W->>A: client_assertion_type=jwt-bearer, client_assertion=JWT Note over A: iss maps to a trusted issuer row Note over A: JWKS verify, then aud/exp/subject/replay checks A->>A: authenticate AS the bound service_account A-->>W: Authorizer access token ``` ### Request No `client_id` and no `client_secret` — the client is derived from the trusted issuer the assertion's `iss` resolves to. Presenting a `client_assertion` together with any other authentication method is rejected ([RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749) §2.3). | Parameter | Value | |-----------|-------| | `client_assertion_type` | `urn:ietf:params:oauth:client-assertion-type:jwt-bearer` (K8s SA tokens, cloud/generic OIDC tokens) or `urn:ietf:params:oauth:client-assertion-type:jwt-spiffe` (SPIFFE JWT-SVIDs) | | `client_assertion` | The external JWT itself | ### Trusted issuers (admin API) An assertion is only accepted if its `iss` matches a **trusted issuer** the admin has registered and bound to a specific service account. Super-admin GraphQL operations (also on `AuthorizerAdminService` gRPC/REST): | Operation | Type | Purpose | |-----------|------|---------| | `_add_trusted_issuer` | mutation | Register an issuer for a service account | | `_update_trusted_issuer` | mutation | Update `name`, `jwks_url`, `expected_aud`, `allowed_subjects`, `is_active` | | `_delete_trusted_issuer` | mutation | Remove the issuer | | `_trusted_issuer` | query | Fetch one by `id` | | `_trusted_issuers` | query | Paginated list, optionally filtered by `service_account_id` | Fields: | Field | Notes | |-------|-------| | `service_account_id` | Internal `id` of the `service_account` client this issuer authenticates | | `issuer_url` | Must equal the assertion's `iss` claim exactly. Globally unique across all trusted issuers (including per-org SSO connections). **Under `static_jwks_url` this is a matching key, not an address — Authorizer never fetches it.** Only `oidc_discovery` dials it (for `{issuer_url}/.well-known/openid-configuration`). That is what lets a private cluster issuer like `https://kubernetes.default.svc` work with a [mirrored JWKS](#clusters-on-the-default-issuer) | | `key_source_type` | `oidc_discovery` (fetch `jwks_uri` from `{issuer_url}/.well-known/openid-configuration`) or `static_jwks_url` (fetch `jwks_url` directly — required when the issuer's discovery document is not reachable) | | `jwks_url` | Required for `static_jwks_url` | | `expected_aud` | The `aud` the assertion **must** contain exactly — set it to your Authorizer URL and mint tokens with that audience, so a token minted for another service can never be replayed here | | `subject_claim` | Claim that identifies the workload; defaults to `sub` | | `allowed_subjects` | Comma-separated **exact-match** subject allow-list. **Empty = deny-all** — a row with no subjects authenticates nobody | | `issuer_type` | `kubernetes_sa` \| `spiffe_jwt` \| `oidc` \| `cloud_oidc` | > JWKS/discovery fetches use an SSRF-hardened HTTP client — host-pinned, redirects refused, response size capped, and private/loopback/link-local addresses rejected. **Whatever Authorizer fetches must therefore be publicly routable**, which for Kubernetes depends entirely on the cluster's issuer — see [Kubernetes ServiceAccount tokens](#kubernetes-serviceaccount-tokens). > > `spiffe_bundle_endpoint` has no implementation and is **rejected at write time** with `key_source_type "spiffe_bundle_endpoint" is not implemented yet` — use `oidc_discovery` or `static_jwks_url` for SPIFFE issuers. `spiffe_refresh_hint_seconds` is stored but not yet honoured at runtime. ### Validation rules Every check is fail-closed, and every rejection returns the same generic `invalid_client` so no check leaks which one failed: | Check | Rule | |-------|------| | Algorithm | Asymmetric only (`RS*`, `PS*`, `ES*`); `alg:none` and `HS*` rejected (RFC 8725) | | Signature | Verified against the issuer's JWKS (cached 10 minutes) | | Issuer | `iss` must resolve to an **active** client-assertion trust row — a per-org [SSO issuer](./org-sso-oidc) at the same URL can never authenticate an OAuth client | | Audience | `aud` must contain the row's `expected_aud` exactly | | Lifetime | `exp` and `iat` required; declared lifetime (`exp − iat`) must be ≤ 1 hour; `exp`/`nbf`/`iat` checked with 60 s clock skew | | Subject | `subject_claim` value must exactly match an `allowed_subjects` entry (never prefix/substring); empty list is deny-all | | Replay | Assertions are **single-use** — keyed by `jti`, or by `(iss, sub, iat, exp)` when the issuer omits one ([RFC 7523](https://www.rfc-editor.org/rfc/rfc7523) permits it), held until the token's `exp`. Kubernetes projected ServiceAccount tokens **do** carry a `jti` and key on it | | Type match | `jwt-bearer` assertions only match non-SPIFFE rows; `jwt-spiffe` only matches `spiffe_jwt` rows | | Bound client | Must exist, be active, and be a `service_account` | Because assertions are single-use, **mint a fresh platform token per token-endpoint call** (Kubernetes TokenRequest API, SPIFFE Workload API) rather than re-presenting a cached one. ### Kubernetes ServiceAccount tokens Kubernetes clusters are OIDC issuers: projected ServiceAccount tokens are JWTs signed by the cluster, with `iss` = the cluster's issuer URL and `sub` = `system:serviceaccount::`. #### Does my cluster work out of the box? Three independent questions decide it, and they have **different answers on the same cluster** — the issuer being private does not make the apiserver private, or vice versa. Check both addresses first: ```bash kubectl get --raw /.well-known/openid-configuration | jq -r '.issuer, .jwks_uri' kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}'; echo ``` Then read off each column independently. Authorizer's SSRF guard refuses private, loopback and link-local addresses, so "reachable" throughout means *publicly routable from Authorizer*. | | `oidc_discovery` | `static_jwks_url` | TokenReview | |---|---|---|---| | **Decided by** | is the **issuer URL** reachable? | is **any copy of the JWKS** reachable? | is the **apiserver** reachable? | | **EKS / GKE / AKS** (public issuer, e.g. `https://oidc.eks..amazonaws.com/id/…`) | ✅ | ✅ not needed | ✅ with a public API endpoint | | **Self-managed, custom public issuer** (`--service-account-issuer=https://…`) | ✅ | ✅ not needed | depends on the endpoint | | **Default issuer** — `https://kubernetes.default.svc.cluster.local` (kubeadm, kind, k3d) | ❌ discovery lives at a private URL | ✅ point it at a reachable copy — the apiserver itself if that is public, otherwise a [mirror](#clusters-on-the-default-issuer) | depends on the endpoint | | **Any cluster, private API endpoint only** | per the issuer, above | per the JWKS, above | ❌ and there is no workaround — leave `enable_token_review` off | Two things worth reading off that table, because they are easy to get backwards: - **A private issuer does not mean the feature is unavailable.** It rules out `oidc_discovery` only. `issuer_url` is matched against the token's `iss` and never fetched under `static_jwks_url`, so it can stay as the cluster's own unroutable value while the keys come from anywhere reachable. - **A private issuer does not imply a private apiserver.** A kubeadm cluster on the default issuer can still have a publicly-reachable control-plane endpoint, in which case TokenReview works and `static_jwks_url` can point straight at `/openid/v1/jwks` with no mirror at all. If your issuer is an `https://` URL on a public domain, the first two rows apply and registration is a two-field job. #### Clusters on the default issuer A cluster left on the upstream default publishes `https://kubernetes.default.svc.cluster.local` as its issuer. That name is a **cluster-internal DNS record**, served by CoreDNS to pods only — `.cluster.local` is not a public zone, and nothing outside the cluster resolves it. So `oidc_discovery` is out, because the discovery document lives under that URL. It fails for a different reason depending on where Authorizer runs, which is worth knowing because the error text differs: | Authorizer runs | What happens | Error you see | |---|---|---| | Outside the cluster | The name does not resolve at all (`NXDOMAIN`) | `failed to resolve host` | | Inside the cluster | CoreDNS resolves it to the `kubernetes` Service ClusterIP — `10.96.0.1` on a default `--service-cluster-ip-range` — which is RFC 1918 | `requests to private/internal networks are not allowed` | That leaves `static_jwks_url`, and the only question is whether Authorizer can reach a copy of the cluster's keys. **Check the apiserver first: if your control-plane endpoint is publicly reachable, point `jwks_url` straight at `https:///openid/v1/jwks` and skip the rest of this section.** A mirror is only needed when it is not — a kind or k3d cluster, or any control plane on a private network. The fix needs no code and no exception: **publish the cluster's public keys somewhere reachable and point `jwks_url` at that.** It works because `issuer_url` is only matched against the token's `iss` and is never dialed, so it can stay as the cluster's own unroutable issuer. This is the same shape AWS IRSA uses — the JWKS in public object storage, the apiserver never exposed. ```bash # 1. Export the cluster's PUBLIC keys. Nothing secret is in this document. kubectl get --raw /openid/v1/jwks > jwks.json # 2. Host it anywhere publicly reachable — object storage, your CDN, a static host. aws s3 cp jwks.json s3://my-bucket/clusters/prod/jwks.json --acl public-read ``` ```graphql mutation { _add_trusted_issuer( params: { service_account_id: "CLIENT_UUID" name: "prod-cluster payments-worker" # The cluster's own issuer — matched against `iss`, never fetched. issuer_url: "https://kubernetes.default.svc.cluster.local" key_source_type: "static_jwks_url" jwks_url: "https://my-bucket.s3.amazonaws.com/clusters/prod/jwks.json" expected_aud: "https://your-authorizer.example" allowed_subjects: "system:serviceaccount:payments:worker" issuer_type: "kubernetes_sa" } ) { id } } ``` :::warning Refresh the mirror when the cluster rotates its keys A mirror is only as current as whatever refreshes it. Kubernetes rotates ServiceAccount signing keys, and a stale mirror fails in both directions: **tokens signed with a new key stop validating** (an outage), and **a retired key that is still published keeps validating tokens it should not** (a security gap). Authorizer caches a fetched JWKS for 10 minutes, so its own staleness is bounded — the mirror's is not. Refresh it as part of whatever rotates the cluster keys, or on a schedule shorter than your rotation period. If you cannot commit to that, prefer a cluster with a public issuer. ::: #### 1. Register the trusted issuer For a cluster with a public issuer (the common case), `oidc_discovery` needs no JWKS handling at all: ```graphql mutation { _add_trusted_issuer( params: { service_account_id: "CLIENT_UUID" # the service_account client's internal id name: "prod-cluster payments-worker" issuer_url: "https://oidc.eks.eu-west-1.amazonaws.com/id/EXAMPLE" key_source_type: "oidc_discovery" expected_aud: "https://your-authorizer.example" allowed_subjects: "system:serviceaccount:payments:worker" issuer_type: "kubernetes_sa" } ) { id issuer_url is_active } } ``` #### 2. Project a token with the right audience ```yaml volumes: - name: authorizer-token projected: sources: - serviceAccountToken: path: authorizer-token audience: https://your-authorizer.example # must equal expected_aud expirationSeconds: 3600 # ≤ the 1-hour lifetime ceiling ``` #### 3. Authenticate ```bash JWT=$(cat /var/run/secrets/tokens/authorizer-token) curl -s -X POST $AUTHORIZER_URL/oauth/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials" \ --data-urlencode "client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer" \ --data-urlencode "client_assertion=$JWT" \ -d "scope=read:payments" ``` For testing: `kubectl create token worker -n payments --audience=https://your-authorizer.example --duration=10m`. #### Online hardening: Kubernetes TokenReview Offline JWKS validation proves the token was signed by the cluster — **not** that the bound Pod/ServiceAccount still exists. A deleted pod's not-yet-expired token would still verify. For high-security workloads a trust row can opt in to online validation via `enable_token_review` + `kubernetes_api_server_url` — admin-settable fields on `_add_trusted_issuer` / `_update_trusted_issuer` (`kubernetes_api_server_url` must be a non-empty `https` URL whenever `enable_token_review` is `true`, checked at write time): after the offline checks pass, Authorizer calls the cluster's `authentication.k8s.io/v1` [TokenReview](https://kubernetes.io/docs/reference/kubernetes-api/authentication-resources/token-review-v1/) API and rejects the assertion fail-closed unless the apiserver reports it still authenticated. ```graphql mutation { _update_trusted_issuer( params: { id: "TRUSTED_ISSUER_UUID" enable_token_review: true kubernetes_api_server_url: "https://" } ) { id enable_token_review kubernetes_api_server_url } } ``` - Authorizer authenticates the TokenReview call with its **own** in-cluster ServiceAccount token, which needs the `system:auth-delegator` ClusterRole. - The apiserver URL goes through the same SSRF-hardened client, so only a **publicly-routable apiserver endpoint** works — `https://kubernetes.default.svc` (a private ClusterIP) is rejected by design. Unlike key fetch, there is no mirror equivalent here: TokenReview is a live call to your apiserver. A cluster without a reachable API endpoint cannot use it, and should leave `enable_token_review` off — offline JWKS validation still authenticates the workload. - `kubernetes_api_server_url` is **security-sensitive**: Authorizer authenticates that call with its own in-cluster ServiceAccount token, so whatever host you configure receives that credential. Treat it as a trusted-host field, and keep Authorizer's ClusterRole to `system:auth-delegator` (TokenReview only) so the credential grants nothing else. ### SPIFFE JWT-SVIDs (preview) For workloads in a [SPIFFE/SPIRE](https://spiffe.io) trust domain, the JWT-SVID is the client credential (per `draft-ietf-oauth-spiffe-client-auth` — an expired individual draft, so this ships as a **preview**). Two differences from the generic path: - `client_assertion_type` is `urn:ietf:params:oauth:client-assertion-type:jwt-spiffe` and the trust row's `issuer_type` must be `spiffe_jwt` — the profiles cannot be crossed. - `iss` is the **SPIRE server**, and `sub` is the workload's **SPIFFE ID** (`spiffe://…`) — `iss ≠ sub` is expected. The subject must be a `spiffe://` URI and appear exactly in `allowed_subjects`. Register the issuer with `issuer_url` set to the SPIRE server's configured `jwt_issuer` and point the key source at the [SPIRE OIDC Discovery Provider](https://spiffe.io/docs/latest/keyless/) (`oidc_discovery`, or `static_jwks_url` at its keys endpoint), with `issuer_type: "spiffe_jwt"` and the workload's SPIFFE ID in `allowed_subjects`. ```bash # Fetch a fresh JWT-SVID from the local SPIRE agent (each fetch mints a new one) SVID=$(spire-agent api fetch jwt \ -audience https://your-authorizer.example -output json | jq -r '.[0].svids[0].svid') curl -s -X POST $AUTHORIZER_URL/oauth/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials" \ --data-urlencode "client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-spiffe" \ --data-urlencode "client_assertion=$SVID" \ -d "scope=read:payments" ``` ### Errors | Error | Cause | |-------|-------| | `invalid_request` | Unsupported `client_assertion_type`, or more than one client authentication method presented | | `invalid_client` | Any assertion validation failure (deliberately indistinguishable) | | `unauthorized_client` | The bound client is not a `service_account` for this grant | | `invalid_scope` | Requested scope outside the client's [`allowed_scopes`](../core/client-registry) | --- ## Getting Started (Sdks) The Authorizer Flutter SDK has not been released yet. The [repository](https://github.com/authorizerdev/authorizer-flutter-sdk) is a placeholder — it contains no source code, and there is no package on pub.dev. Until it ships, call the server directly from Dart: every SDK operation is available over the [REST endpoints](/core/endpoints) and the [GraphQL API](/core/graphql-api), which work with any HTTP client (`package:http`, Dio, and so on). For browser-based OAuth flows, see [OAuth 2.0 / OIDC](/core/oauth2-oidc). --- ## Protocols & Admin API _Added in authorizer-go for Authorizer **2.3.0-rc.9**._ ### Protocol selection The user client can talk to the server over three wire protocols. **`graphql` is the default** and is 100% backward compatible — existing code keeps working unchanged. | Protocol | Transport | Notes | | ------------------ | ------------------------------- | ---------------------------------------------- | | `ProtocolGraphQL` | `POST /graphql` | Default. | | `ProtocolREST` | Typed `POST/GET /v1/...` routes | Same flat responses as GraphQL. | | `ProtocolGRPC` | Generated gRPC stub | Uses a **separate endpoint** (default `:9091`). | Pass `WithProtocol` to `NewAuthorizerClient`. Public methods work over every protocol, and all three return **identical flat response shapes**. `GetToken` and `RevokeToken` always use REST (see the OAuth note below). ```go // REST (default endpoint, no extra config) client, err := authorizer.NewAuthorizerClient( "YOUR_CLIENT_ID", "YOUR_AUTHORIZER_URL", "", nil, authorizer.WithProtocol(authorizer.ProtocolREST), ) ``` #### gRPC gRPC listens on its own port, separate from the HTTP URL. When `WithGRPCEndpoint` is omitted, the target is derived from the Authorizer URL's host with the default gRPC port `9091`. ```go client, err := authorizer.NewAuthorizerClient( "YOUR_CLIENT_ID", "https://your-instance.authorizer.dev", "", nil, authorizer.WithProtocol(authorizer.ProtocolGRPC), authorizer.WithGRPCEndpoint("your-instance.authorizer.dev:9091"), // optional ) if err != nil { panic(err) } res, err := client.Login(&authorizer.LoginRequest{Email: authorizer.NewStringRef("user@example.com"), Password: "Abc@123"}) ``` > OAuth endpoints (`/oauth/token`, `/oauth/revoke`) always use REST regardless of the > selected protocol. ### Admin client The admin API is a **separate client** constructed with the admin secret (the value of `--admin-secret`). Admin auth is sent on every call as the `x-authorizer-admin-secret` header (gRPC: metadata key `x-authorizer-admin-secret`). ```go admin, err := authorizer.NewAuthorizerAdminClient( "https://your-instance.authorizer.dev", "YOUR_ADMIN_SECRET", ) if err != nil { panic(err) } // List users res, err := admin.Users(&authorizerv1.UsersRequest{}) if err != nil { panic(err) } for _, u := range res.Users { fmt.Println(u.Email) } ``` Request/response types for the proto-backed methods come from the generated package `authorizerv1 "github.com/authorizerdev/authorizer-proto-go/authorizer/v1"`. It is a public module of its own, so application code can import it directly — it is pulled in transitively when you `go get github.com/authorizerdev/authorizer-go/v2`. The Go-native admin operations (organizations, org SSO connections, SCIM, org domains — see below) declare their request/response types directly in the top-level `authorizer` package instead. #### Admin client options | Option | Description | | ---------------------------- | ------------------------------------------------------------------------ | | `WithAdminProtocol(p)` | Wire transport. Defaults to `ProtocolGraphQL`. | | `WithAdminGRPCEndpoint(addr)`| gRPC target (default: URL host + `:9091`). | | `WithAdminExtraHeaders(h)` | Extra headers sent on every admin request. | ```go admin, err := authorizer.NewAuthorizerAdminClient( "https://your-instance.authorizer.dev", "YOUR_ADMIN_SECRET", authorizer.WithAdminProtocol(authorizer.ProtocolGRPC), authorizer.WithAdminGRPCEndpoint("your-instance.authorizer.dev:9091"), ) ``` #### Admin methods Each method declares which protocols support it. Calling a method on an unsupported protocol raises a clear error early (e.g. _"AdminMeta not available over graphql; use grpc or rest"_) rather than emitting a 404. The protocol columns below also apply to the Python and JS admin clients (JS supports graphql + rest only). > **⚠ Destructive:** `DeleteUser`, `DeleteWebhook`, `DeleteEmailTemplate`, > `FgaWriteModel` (overwrites the model), `FgaDeleteTuples`, `FgaReset` (wipes all FGA > data), `DeleteClient`, `DeleteTrustedIssuer`, `DeleteSamlServiceProvider`, > `RetireSamlIdpKey`, `DeleteOrganization`, `DeleteOrgOIDCConnection`, > `DeleteOrgSAMLConnection`, `DeleteScimEndpoint`, and `DeleteOrgDomain` > permanently change or remove data. ##### Auth, session & meta | Method | Description | grpc | rest | gql | | ------------- | -------------------------------------------- | :--: | :--: | :-: | | `AdminLogin` | Exchange the admin secret for a session. | ✓ | ✓ | ✓ | | `AdminLogout` | End the admin session. | ✓ | ✓ | ✓ | | `AdminSession`| Get the current admin session. | ✓ | ✓ | ✓ | | `AdminMeta` | Server metadata / feature flags. | ✓ | ✓ | ✓ | ##### Users & access | Method | Description | grpc | rest | gql | | ----------------------- | --------------------------------------------- | :--: | :--: | :-: | | `Users` | List users (paginated). | ✓ | ✓ | ✓ | | `User` | Get a single user. | ✓ | ✓ | ✓ | | `UpdateUser` | Update a user. | ✓ | ✓ | ✓ | | `DeleteUser` | **Delete a user.** | ✓ | ✓ | ✓ | | `VerificationRequests` | List pending verification requests. | ✓ | ✓ | ✓ | | `RevokeAccess` | Revoke a user's access. | ✓ | ✓ | ✓ | | `EnableAccess` | Re-enable a user's access. | ✓ | ✓ | ✓ | | `InviteMembers` | Invite members by email. | ✓ | ✓ | ✓ | ##### Webhooks | Method | Description | grpc | rest | gql | | --------------- | -------------------------------- | :--: | :--: | :-: | | `AddWebhook` | Create a webhook. | ✓ | ✓ | ✓ | | `UpdateWebhook` | Update a webhook. | ✓ | ✓ | ✓ | | `DeleteWebhook` | **Delete a webhook.** | ✓ | ✓ | ✓ | | `GetWebhook` | Get a single webhook. | ✓ | ✓ | ✓ | | `Webhooks` | List webhooks. | ✓ | ✓ | ✓ | | `WebhookLogs` | List webhook delivery logs. | ✓ | ✓ | ✓ | | `TestEndpoint` | Send a test event to a webhook. | ✓ | ✓ | ✓ | ##### Email templates | Method | Description | grpc | rest | gql | | ---------------------- | ---------------------------- | :--: | :--: | :-: | | `AddEmailTemplate` | Create an email template. | ✓ | ✓ | ✓ | | `UpdateEmailTemplate` | Update an email template. | ✓ | ✓ | ✓ | | `DeleteEmailTemplate` | **Delete an email template.**| ✓ | ✓ | ✓ | | `EmailTemplates` | List email templates. | ✓ | ✓ | ✓ | ##### Audit | Method | Description | grpc | rest | gql | | ----------- | ----------------- | :--: | :--: | :-: | | `AuditLogs` | List audit logs. | ✓ | ✓ | ✓ | ##### FGA admin | Method | Description | grpc | rest | gql | | ----------------- | ---------------------------------------- | :--: | :--: | :-: | | `FgaGetModel` | Get the current FGA model. | ✓ | ✓ | ✓ | | `FgaWriteModel` | **Write/overwrite the FGA model.** | ✓ | ✓ | ✓ | | `FgaWriteTuples` | Write relationship tuples. | ✓ | ✓ | ✓ | | `FgaDeleteTuples` | **Delete relationship tuples.** | ✓ | ✓ | ✓ | | `FgaReadTuples` | Read relationship tuples. | ✓ | ✓ | ✓ | | `FgaListUsers` | List users with a relation to an object. | ✓ | ✓ | ✓ | | `FgaExpand` | Expand a relation into its userset. | ✓ | ✓ | ✓ | | `FgaReset` | **Reset all FGA data.** | ✓ | ✓ | ✓ | ##### OAuth clients (machine-to-machine / workload identity) Since v2.4.0 clients carry `BackchannelTokenDeliveryMode` (`"poll"` when the client may use [CIBA](../../enterprise/ciba)), and `CreateClient`/`UpdateClient` accept it. Reading it needs **server 2.5.0+**: against an older server, the client methods fail over GraphQL with *Cannot query field* (REST and gRPC are unaffected). | Method | Description | grpc | rest | gql | | -------------------- | --------------------------------------------------------------------------------------- | :--: | :--: | :-: | | `CreateClient` | Provision a new machine/workload identity (service account). `client_secret` is returned **once**. | ✓ | ✓ | ✓ | | `UpdateClient` | Update a client's metadata, scopes or active flag. | ✓ | ✓ | ✓ | | `DeleteClient` | **Delete a client.** Tokens already issued to it stop being honoured. | ✓ | ✓ | ✓ | | `RotateClientSecret` | Issue a new secret for a client. Returned once; the old secret keeps validating during the grace window. | ✓ | ✓ | ✓ | | `GetClient` | Get a single client by id (`client_secret` never returned). | ✓ | ✓ | ✓ | | `Clients` | List clients (paginated). | ✓ | ✓ | ✓ | ##### Trusted issuers | Method | Description | grpc | rest | gql | | ---------------------- | ------------------------------------------------------------------------------------------------------ | :--: | :--: | :-: | | `AddTrustedIssuer` | Register an external token issuer (K8s service account, [SPIFFE](https://spiffe.io), OIDC) allowed to authenticate as a service account via JWT-bearer assertions. | ✓ | ✓ | ✓ | | `UpdateTrustedIssuer` | Update a trusted issuer. | ✓ | ✓ | ✓ | | `DeleteTrustedIssuer` | **Delete a trusted issuer.** Assertions from it stop authenticating immediately. | ✓ | ✓ | ✓ | | `GetTrustedIssuer` | Get a single trusted issuer by id. | ✓ | ✓ | ✓ | | `TrustedIssuers` | List trusted issuers (paginated), optionally filtered by `service_account_id`. | ✓ | ✓ | ✓ | ##### SAML (service providers & IdP keys) | Method | Description | grpc | rest | gql | | ---------------------------- | -------------------------------------------------------------------------------------------------| :--: | :--: | :-: | | `CreateSamlServiceProvider` | Register a downstream [SAML 2.0](https://www.oasis-open.org/standard/saml/) SP that Authorizer (acting as IdP) issues signed assertions to. | ✓ | ✓ | ✓ | | `UpdateSamlServiceProvider` | Update a downstream SP's name, endpoints, certificate, attribute mapping, or active state. | ✓ | ✓ | ✓ | | `DeleteSamlServiceProvider` | **Delete a downstream SP.** SSO assertions to it stop being issued immediately. | ✓ | ✓ | ✓ | | `GetSamlServiceProvider` | Get a single downstream SP by id. | ✓ | ✓ | ✓ | | `ListSamlServiceProviders` | List downstream SPs for an org (paginated). | ✓ | ✓ | ✓ | | `RotateSamlIdpCert` | Generate a new current signing keypair for an org's SAML IdP, demoting the previous current key. | ✓ | ✓ | ✓ | | `RetireSamlIdpKey` | **Retire a published-but-not-signing SAML IdP key.** It stops being published in IdP metadata. | ✓ | ✓ | ✓ | | `ListSamlIdpKeys` | List all SAML IdP signing keys for an org. | ✓ | ✓ | ✓ | | `ImportSamlSpMetadata` | Parse pasted SP metadata XML into fields to prefill a create call. Does not create a record or fetch remotely. | ✓ | ✓ | ✓ | ##### Organizations & members Organizations, members, SSO connections, SCIM endpoints and verified domains work over every protocol as of server 2.4.0. Their types are declared directly in the Go SDK rather than proto-generated — `Organization`, `OrgMember`, `CreateOrganizationRequest`, `ListOrganizationsRequest`, etc. — because these operations predate the proto; the signatures were kept when the REST/gRPC transports were added. | Method | Description | grpc | rest | gql | | --------------------- | ----------------------------------------------------| :--: | :--: | :-: | | `CreateOrganization` | Create an organization. `Name` must be a unique, URL-safe slug. | ✓ | ✓ | ✓ | | `UpdateOrganization` | Update an organization. | ✓ | ✓ | ✓ | | `DeleteOrganization` | **Delete an organization** and its memberships/connections. | ✓ | ✓ | ✓ | | `GetOrganization` | Get a single organization by id. | ✓ | ✓ | ✓ | | `Organizations` | List organizations (paginated). | ✓ | ✓ | ✓ | | `AddOrgMember` | Add a user to an organization. | ✓ | ✓ | ✓ | | `RemoveOrgMember` | Remove a user from an organization. | ✓ | ✓ | ✓ | | `OrgMembers` | List an organization's members (paginated). | ✓ | ✓ | ✓ | | `UserOrganizations` | List a user's organizations, with per-org roles (paginated). | ✓ | ✓ | ✓ | `Organizations`, `OrgMembers` and `OrgDomains` (below) take pagination via this SDK's own `*PaginationRequest` type directly on the request — a single level, matching the proto shape everywhere else in the SDK: ```go res, err := admin.Organizations(&authorizer.ListOrganizationsRequest{ Pagination: &authorizer.PaginationRequest{Limit: 20, Page: 1}, }) members, err := admin.OrgMembers(&authorizer.ListOrgMembersRequest{ OrgID: "org_123", Pagination: &authorizer.PaginationRequest{Limit: 20, Page: 1}, }) ``` ##### Org SSO connections (OIDC & SAML) Upstream SSO an organization's members sign in through. | Method | Description | grpc | rest | gql | | ------------------------------ | ------------------------------------------------------------------------| :--: | :--: | :-: | | `CreateOrgOIDCConnection` | Create an org's upstream OIDC SSO connection. | ✓ | ✓ | ✓ | | `UpdateOrgOIDCConnection` | Update it. Supplying `ClientSecret` rotates it; omitting leaves it intact. | ✓ | ✓ | ✓ | | `DeleteOrgOIDCConnection` | **Delete it.** SSO logins through it stop working immediately. | ✓ | ✓ | ✓ | | `GetOrgOIDCConnection` | Get it by id or by org id (supply exactly one). | ✓ | ✓ | ✓ | | `CreateOrgSAMLConnection` | Create an org's upstream SAML SSO connection. | ✓ | ✓ | ✓ | | `UpdateOrgSAMLConnection` | Update it. Supplying `IdpCertificate` replaces it; omitting leaves it intact. | ✓ | ✓ | ✓ | | `DeleteOrgSAMLConnection` | **Delete it.** SSO logins through it stop working immediately. | ✓ | ✓ | ✓ | | `GetOrgSAMLConnection` | Get it by id or by org id (supply exactly one). | ✓ | ✓ | ✓ | ##### SCIM provisioning | Method | Description | grpc | rest | gql | | -------------------- | --------------------------------------------------------------------------------| :--: | :--: | :-: | | `CreateScimEndpoint` | Provision a SCIM endpoint for an organization. The bearer token is returned **once**. | ✓ | ✓ | ✓ | | `RotateScimToken` | Rotate the SCIM endpoint's bearer token. New token returned once; old one stops validating. | ✓ | ✓ | ✓ | | `DeleteScimEndpoint` | **Delete an organization's SCIM endpoint.** The IdP's provisioning token stops working immediately. | ✓ | ✓ | ✓ | | `GetScimEndpoint` | Get an organization's SCIM endpoint (the bearer token is never returned). | ✓ | ✓ | ✓ | ##### Org domains (home realm discovery) Verified DNS-domain-to-organization mappings used for home realm discovery. | Method | Description | grpc | rest | gql | | ------------------------ | --------------------------------------------------------------------------------------------------| :--: | :--: | :-: | | `RequestOrgDomain` | Start domain verification, returning the DNS TXT record the tenant must publish to prove control. | ✓ | ✓ | ✓ | | `VerifyOrgDomain` | Check the DNS TXT challenge and, if satisfied, verify the domain. | ✓ | ✓ | ✓ | | `AddVerifiedOrgDomain` | Directly register a verified domain, bypassing the DNS TXT challenge. Super-admin only. | ✓ | ✓ | ✓ | | `DeleteOrgDomain` | **Remove a verified domain.** Logins relying on it for home realm discovery stop resolving to the org. | ✓ | ✓ | ✓ | | `OrgDomains` | List an organization's verified domains (paginated). | ✓ | ✓ | ✓ | ```go domains, err := admin.OrgDomains(&authorizer.ListOrgDomainsRequest{ OrgID: "org_123", Pagination: &authorizer.PaginationRequest{Limit: 20, Page: 1}, }) ``` ##### OAuth clients (machine-to-machine / workload identity) Since v2.4.0 clients carry `BackchannelTokenDeliveryMode` (`"poll"` when the client may use [CIBA](../../enterprise/ciba)), and `CreateClient`/`UpdateClient` accept it. Reading it needs **server 2.5.0+**: against an older server, the client methods fail over GraphQL with *Cannot query field* (REST and gRPC are unaffected). | Method | Description | grpc | rest | gql | | -------------------- | --------------------------------------------------------------------------------------- | :--: | :--: | :-: | | `CreateClient` | Provision a new machine/workload identity (service account). `client_secret` is returned **once**. | ✓ | ✓ | ✓ | | `UpdateClient` | Update a client's metadata, scopes or active flag. | ✓ | ✓ | ✓ | | `DeleteClient` | **Delete a client.** Tokens already issued to it stop being honoured. | ✓ | ✓ | ✓ | | `RotateClientSecret` | Issue a new secret for a client. Returned once; the old secret keeps validating during the grace window. | ✓ | ✓ | ✓ | | `GetClient` | Get a single client by id (`client_secret` never returned). | ✓ | ✓ | ✓ | | `Clients` | List clients (paginated). | ✓ | ✓ | ✓ | ##### Trusted issuers | Method | Description | grpc | rest | gql | | ---------------------- | ------------------------------------------------------------------------------------------------------ | :--: | :--: | :-: | | `AddTrustedIssuer` | Register an external token issuer (K8s service account, SPIFFE, OIDC) allowed to authenticate as a service account via JWT-bearer assertions. | ✓ | ✓ | ✓ | | `UpdateTrustedIssuer` | Update a trusted issuer. | ✓ | ✓ | ✓ | | `DeleteTrustedIssuer` | **Delete a trusted issuer.** Assertions from it stop authenticating immediately. | ✓ | ✓ | ✓ | | `GetTrustedIssuer` | Get a single trusted issuer by id. | ✓ | ✓ | ✓ | | `TrustedIssuers` | List trusted issuers (paginated), optionally filtered by `service_account_id`. | ✓ | ✓ | ✓ | ##### SAML (service providers & IdP keys) | Method | Description | grpc | rest | gql | | ---------------------------- | -------------------------------------------------------------------------------------------------| :--: | :--: | :-: | | `CreateSamlServiceProvider` | Register a downstream SAML 2.0 SP that Authorizer (acting as IdP) issues signed assertions to. | ✓ | ✓ | ✓ | | `UpdateSamlServiceProvider` | Update a downstream SP's name, endpoints, certificate, attribute mapping, or active state. | ✓ | ✓ | ✓ | | `DeleteSamlServiceProvider` | **Delete a downstream SP.** SSO assertions to it stop being issued immediately. | ✓ | ✓ | ✓ | | `GetSamlServiceProvider` | Get a single downstream SP by id. | ✓ | ✓ | ✓ | | `ListSamlServiceProviders` | List downstream SPs for an org (paginated). | ✓ | ✓ | ✓ | | `RotateSamlIdpCert` | Generate a new current signing keypair for an org's SAML IdP, demoting the previous current key. | ✓ | ✓ | ✓ | | `RetireSamlIdpKey` | **Retire a published-but-not-signing SAML IdP key.** It stops being published in IdP metadata. | ✓ | ✓ | ✓ | | `ListSamlIdpKeys` | List all SAML IdP signing keys for an org. | ✓ | ✓ | ✓ | | `ImportSamlSpMetadata` | Parse pasted SP metadata XML into fields to prefill a create call. Does not create a record or fetch remotely. | ✓ | ✓ | ✓ | ##### Organizations & members Organizations, members, SSO connections, SCIM endpoints and verified domains have no proto/gRPC or REST RPCs — they are **GraphQL only**. Types are declared directly in the Go SDK (not proto-generated): `Organization`, `OrgMember`, `CreateOrganizationRequest`, `ListOrganizationsRequest`, etc. | Method | Description | grpc | rest | gql | | --------------------- | ----------------------------------------------------| :--: | :--: | :-: | | `CreateOrganization` | Create an organization. `Name` must be a unique, URL-safe slug. | | | ✓ | | `UpdateOrganization` | Update an organization. | | | ✓ | | `DeleteOrganization` | **Delete an organization** and its memberships/connections. | | | ✓ | | `GetOrganization` | Get a single organization by id. | | | ✓ | | `Organizations` | List organizations (paginated). | | | ✓ | | `AddOrgMember` | Add a user to an organization. | | | ✓ | | `RemoveOrgMember` | Remove a user from an organization. | | | ✓ | | `OrgMembers` | List an organization's members (paginated). | | | ✓ | | `UserOrganizations` | List a user's organizations, with per-org roles (paginated). | | | ✓ | `Organizations`, `OrgMembers` and `OrgDomains` (below) take pagination via this SDK's own `*PaginationRequest` type directly on the request — a single level, matching the proto shape everywhere else in the SDK: ```go res, err := admin.Organizations(&authorizer.ListOrganizationsRequest{ Pagination: &authorizer.PaginationRequest{Limit: 20, Page: 1}, }) members, err := admin.OrgMembers(&authorizer.ListOrgMembersRequest{ OrgID: "org_123", Pagination: &authorizer.PaginationRequest{Limit: 20, Page: 1}, }) ``` ##### Org SSO connections (OIDC & SAML) Upstream SSO an organization's members sign in through. **GraphQL only.** | Method | Description | grpc | rest | gql | | ------------------------------ | ------------------------------------------------------------------------| :--: | :--: | :-: | | `CreateOrgOIDCConnection` | Create an org's upstream OIDC SSO connection. | | | ✓ | | `UpdateOrgOIDCConnection` | Update it. Supplying `ClientSecret` rotates it; omitting leaves it intact. | | | ✓ | | `DeleteOrgOIDCConnection` | **Delete it.** SSO logins through it stop working immediately. | | | ✓ | | `GetOrgOIDCConnection` | Get it by id or by org id (supply exactly one). | | | ✓ | | `CreateOrgSAMLConnection` | Create an org's upstream SAML SSO connection. | | | ✓ | | `UpdateOrgSAMLConnection` | Update it. Supplying `IdpCertificate` replaces it; omitting leaves it intact. | | | ✓ | | `DeleteOrgSAMLConnection` | **Delete it.** SSO logins through it stop working immediately. | | | ✓ | | `GetOrgSAMLConnection` | Get it by id or by org id (supply exactly one). | | | ✓ | ##### SCIM provisioning **GraphQL only.** | Method | Description | grpc | rest | gql | | -------------------- | --------------------------------------------------------------------------------| :--: | :--: | :-: | | `CreateScimEndpoint` | Provision a SCIM endpoint for an organization. The bearer token is returned **once**. | | | ✓ | | `RotateScimToken` | Rotate the SCIM endpoint's bearer token. New token returned once; old one stops validating. | | | ✓ | | `DeleteScimEndpoint` | **Delete an organization's SCIM endpoint.** The IdP's provisioning token stops working immediately. | | | ✓ | | `GetScimEndpoint` | Get an organization's SCIM endpoint (the bearer token is never returned). | | | ✓ | ##### Org domains (home realm discovery) Verified DNS-domain-to-organization mappings used for home realm discovery. **GraphQL only.** | Method | Description | grpc | rest | gql | | ------------------------ | --------------------------------------------------------------------------------------------------| :--: | :--: | :-: | | `RequestOrgDomain` | Start domain verification, returning the DNS TXT record the tenant must publish to prove control. | | | ✓ | | `VerifyOrgDomain` | Check the DNS TXT challenge and, if satisfied, verify the domain. | | | ✓ | | `AddVerifiedOrgDomain` | Directly register a verified domain, bypassing the DNS TXT challenge. Super-admin only. | | | ✓ | | `DeleteOrgDomain` | **Remove a verified domain.** Logins relying on it for home realm discovery stop resolving to the org. | | | ✓ | | `OrgDomains` | List an organization's verified domains (paginated). | | | ✓ | ```go domains, err := admin.OrgDomains(&authorizer.ListOrgDomainsRequest{ OrgID: "org_123", Pagination: &authorizer.PaginationRequest{Limit: 20, Page: 1}, }) ``` ##### GraphQL-only extras These are the only admin operations with no proto RPC, so they work **over GraphQL only**: | Method | Description | | ----------------- | ------------------------------------ | | `AdminSignup` | Bootstrap the first admin. | | `UpdateEnv` | **Deprecated server-side** — v2 configures everything via CLI flags; the resolver always errors. | | `GenerateJWTKeys` | Generate a new JWT signing key pair. | --- ## Example ## How to use authorizer as API gateway > Note: This example demonstrates how to use authorizer in middleware for a [go-gin](https://github.com/gin-gonic/gin) server. But logic remains the same under the hood, where you can get auth token from `header` and validate it via authorizer SDK ```go package main import ( "net/http" "strings" authorizer "github.com/authorizerdev/authorizer-go/v2" "github.com/gin-gonic/gin" ) func AuthorizeMiddleware() gin.HandlerFunc { return func(c *gin.Context) { /** for open routes you can add condition here and just return with c.Next() so that it does not validate token for those routes */ authHeader := c.Request.Header.Get("Authorization") tokenSplit := strings.Split(authHeader, " ") defaultHeaders := map[string]string{} authorizerClient, err := authorizer.NewAuthorizerClient("YOUR_CLIENT_ID", "YOUR_AUHTORIZER_URL", "OPTIONAL_REDIRECT_URL", defaultHeaders) if err != nil { // unauthorized c.AbortWithStatusJSON(401, "unauthorized") return } if len(tokenSplit) < 2 || tokenSplit[1] == "" { // unauthorized c.AbortWithStatusJSON(401, "unauthorized") return } res, err := authorizerClient.ValidateJWTToken(&authorizer.ValidateJWTTokenRequest{ TokenType: authorizer.TokenTypeIDToken, Token: tokenSplit[1], }) if err != nil { // unauthorized c.AbortWithStatusJSON(401, "unauthorized") return } if !res.IsValid { // unauthorized c.AbortWithStatusJSON(401, "unauthorized") return } c.Next() } } func main() { router := gin.New() router.Use(AuthorizeMiddleware()) router.GET("/ping", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "pong", }) }) router.Run(":8090") } ``` **CURL command to test go-gin server created in example** Copy JWT ID token from login response of authorizer `login` mutation / social media login and replace `JWT_TOKEN` below ```bash curl --location --request GET 'http://localhost:8090/ping' \ --header 'Authorization: Bearer JWT_TOKEN' ``` ### Object-level authorization with FGA Once the token is validated, you can also ask Authorizer's embedded [OpenFGA](https://openfga.dev) engine whether the caller may act on a **specific object**. The middleware below forwards the caller's `Authorization` header — the server pins the subject from it — and fails closed on any error. See [Authorization (FGA)](/core/authorization) for the model and tuple setup. ```go // RequirePermission gates a route on an FGA check, e.g.: // router.GET("/documents/:id", RequirePermission("can_view"), getDocument) // router.PUT("/documents/:id", RequirePermission("can_edit"), updateDocument) func RequirePermission(relation string) gin.HandlerFunc { return func(c *gin.Context) { res, err := authorizerClient.CheckPermissions(&authorizer.CheckPermissionsRequest{ Checks: []*authorizer.PermissionCheckInput{ {Relation: relation, Object: "document:" + c.Param("id")}, }, }, map[string]string{ // forward the caller's token so the server pins the subject "Authorization": c.Request.Header.Get("Authorization"), }) if err != nil || len(res.Results) == 0 || !res.Results[0].Allowed { // fail closed c.AbortWithStatusJSON(403, "forbidden") return } c.Next() } } ``` To render one page with several action flags (view / edit / delete buttons), batch the checks in one round trip — results come back in order and echo each pair: ```go res, err := authorizerClient.CheckPermissions(&authorizer.CheckPermissionsRequest{ Checks: []*authorizer.PermissionCheckInput{ {Relation: "can_view", Object: "document:1"}, {Relation: "can_edit", Object: "document:1"}, {Relation: "can_delete", Object: "document:1"}, }, }, map[string]string{"Authorization": authHeader}) if err != nil { // fail closed } for _, r := range res.Results { // r.Relation, r.Object, r.Allowed } ``` And for list endpoints, ask once which objects the caller may see and filter your DB query by the result instead of checking one by one: ```go res, err := authorizerClient.ListPermissions(&authorizer.ListPermissionsRequest{ Relation: "can_view", ObjectType: "document", }, map[string]string{"Authorization": authHeader}) // res.Objects => ["document:1", "document:7", ...] ``` --- ## Functions The `AuthorizerClient` provides methods to interact with the Authorizer API. Every method takes a request struct as a parameter and returns a response struct or an error. ```go import "github.com/authorizerdev/authorizer-go/v2" client, err := authorizer.NewAuthorizerClient( "YOUR_CLIENT_ID", "https://your-instance.authorizer.dev", "https://your-app.example.com", nil, ) if err != nil { panic(err) } // Example: Login res, err := client.Login(&authorizer.LoginRequest{ Email: stringPtr("user@example.com"), Password: "Abc@123", }) if err != nil { panic(err) } ``` ### Authentication & user management #### Public methods (no authentication required) | Method | Signature | Returns | | --------------------- | --------------------------------------------------------------- | --------------------------- | | `Login` | `Login(req *LoginRequest) (*AuthTokenResponse, error)` | `*AuthTokenResponse` | | `SignUp` | `SignUp(req *SignUpRequest) (*AuthTokenResponse, error)` | `*AuthTokenResponse` | | `MagicLinkLogin` | `MagicLinkLogin(req *MagicLinkLoginRequest) (*Response, error)` | `*Response` | | `VerifyOTP` | `VerifyOTP(req *VerifyOTPRequest) (*AuthTokenResponse, error)` | `*AuthTokenResponse` | | `VerifyEmail` | `VerifyEmail(req *VerifyEmailRequest) (*AuthTokenResponse, error)` | `*AuthTokenResponse` | | `ResendOTP` | `ResendOTP(req *ResendOTPRequest) (*Response, error)` | `*Response` | | `ResendVerifyEmail` | `ResendVerifyEmail(req *ResendVerifyEmailRequest) (*Response, error)` | `*Response` | | `ForgotPassword` | `ForgotPassword(req *ForgotPasswordRequest) (*ForgotPasswordResponse, error)` | `*ForgotPasswordResponse` | | `ResetPassword` | `ResetPassword(req *ResetPasswordRequest) (*Response, error)` | `*Response` | | `ValidateJWTToken` | `ValidateJWTToken(req *ValidateJWTTokenRequest) (*ValidateJWTTokenResponse, error)` | `*ValidateJWTTokenResponse` | | `ValidateSession` | `ValidateSession(req *ValidateSessionRequest) (*ValidateSessionResponse, error)` | `*ValidateSessionResponse` | | `GetMetaData` | `GetMetaData() (*MetaData, error)` | `*MetaData` | #### Authenticated (pass `headers` map with bearer token) | Method | Signature | Returns | | --------------------- | ------------------------------------------------------------------------------- | ----------------- | | `GetSession` | `GetSession(headers map[string]string) (*AuthTokenResponse, error)` | `*AuthTokenResponse` | | `GetProfile` | `GetProfile(headers map[string]string) (*User, error)` | `*User` | | `UpdateProfile` | `UpdateProfile(req *UpdateProfileRequest, headers map[string]string) (*Response, error)` | `*Response` | | `Logout` | `Logout(headers map[string]string) (*Response, error)` | `*Response` | | `DeactivateAccount` | `DeactivateAccount(headers map[string]string) (*Response, error)` | `*Response` | #### Fine-grained authorization | Method | Signature | Returns | | -------------------- | --------------------------------------------------------------------------- | --------------------------- | | `CheckPermissions` | `CheckPermissions(req *CheckPermissionsRequest, headers map[string]string) (*CheckPermissionsResponse, error)` | `*CheckPermissionsResponse` | | `ListPermissions` | `ListPermissions(req *ListPermissionsRequest, headers map[string]string) (*ListPermissionsResponse, error)` | `*ListPermissionsResponse` | See the dedicated [Fine-Grained Authorization](/sdks/authorizer-go/admin#fga-admin) documentation for details. #### MFA setup & recovery All take a `headers` map with a bearer token (or, if the caller doesn't have one yet, an `email`/`phone_number` pair that resolves the in-progress MFA session cookie instead). | Method | Signature | Returns | | ----------------------- | ---------------------------------------------------------------------- | ------------------- | | `SkipMfaSetup` | `SkipMfaSetup(req *SkipMfaSetupRequest, headers map[string]string) (*AuthTokenResponse, error)` | `*AuthTokenResponse` | | `LockMfa` | `LockMfa(req *LockMfaRequest, headers map[string]string) (*Response, error)` | `*Response` | | `EmailOtpMfaSetup` | `EmailOtpMfaSetup(req *EmailOtpMfaSetupRequest, headers map[string]string) (*Response, error)` | `*Response` | | `SmsOtpMfaSetup` | `SmsOtpMfaSetup(req *SmsOtpMfaSetupRequest, headers map[string]string) (*Response, error)` | `*Response` | | `TotpMfaSetup` | `TotpMfaSetup(req *TotpMfaSetupRequest, headers map[string]string) (*AuthTokenResponse, error)` | `*AuthTokenResponse` | > `LockMfa` has no OTP fallback — it locks the account and requires admin recovery afterward. #### WebAuthn / passkeys | Method | Signature | Returns | | ---------------------------------- | ----------- | ---------------------------------------- | | `WebauthnRegistrationOptions` | `WebauthnRegistrationOptions(req *WebauthnRegistrationOptionsRequest, headers map[string]string) (*WebauthnRegistrationOptionsResponse, error)` | `*WebauthnRegistrationOptionsResponse` | | `WebauthnRegistrationVerify` | `WebauthnRegistrationVerify(req *WebauthnRegistrationVerifyRequest, headers map[string]string) (*AuthTokenResponse, error)` | `*AuthTokenResponse` | | `WebauthnLoginOptions` | `WebauthnLoginOptions(email *string) (*WebauthnLoginOptionsResponse, error)` | `*WebauthnLoginOptionsResponse` | | `WebauthnLoginVerify` | `WebauthnLoginVerify(req *WebauthnLoginVerifyRequest) (*AuthTokenResponse, error)` | `*AuthTokenResponse` | | `WebauthnDeleteCredential` | `WebauthnDeleteCredential(id string, headers map[string]string) (*Response, error)` | `*Response` | | `WebauthnCredentials` | `WebauthnCredentials(headers map[string]string) ([]*WebauthnCredentialInfo, error)` | `[]*WebauthnCredentialInfo` | `WebauthnRegistrationOptions`/`WebauthnLoginOptions` return JSON-encoded `options` strings to feed straight to the browser's `navigator.credentials.create()` / `.get()`; `WebauthnRegistrationVerify`/`WebauthnLoginVerify` take the JSON-encoded credential response back. `WebauthnDeleteCredential` permanently deletes a registered passkey. `WebauthnCredentials` lists the authenticated caller's own registered passkeys. #### OAuth (REST) | Method | Signature | Returns | | -------------- | ------------------------------------------ | ------------------ | | `GetToken` | `GetToken(req *GetTokenRequest) (*TokenResponse, error)` | `*TokenResponse` | | `RevokeToken` | `RevokeToken(req *RevokeTokenRequest) (*Response, error)` | `*Response` | | `Revoke` | `Revoke(req *RevokeRequest) (*Response, error)` | `*Response` | `GetToken` posts a form-encoded (`application/x-www-form-urlencoded`) request to `/oauth/token` and supports four grants: `authorization_code` (default, needs `code` + `code_verifier`), `refresh_token`, `client_credentials` ([RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749) §4.4), and [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) token exchange. The `client_credentials` and token-exchange grants are **machine / agent-to-agent flows — server-side only**: never send `client_secret`, `client_assertion`, or a `subject_token`/`actor_token` to untrusted or browser code. ##### Machine-to-machine (client_credentials) Get a token for a service account / machine identity created via the [admin `CreateClient`](./admin) method: ```go import "github.com/authorizerdev/authorizer-go/v2" machine, err := authorizer.NewAuthorizerClient( "SERVICE_CLIENT_ID", "https://your-instance.authorizer.dev", "https://your-app.example.com", nil, ) if err != nil { panic(err) } token, err := machine.GetToken(&authorizer.GetTokenRequest{ GrantType: stringPtr(authorizer.GrantTypeClientCredentials), ClientSecret: stringPtr("SERVICE_CLIENT_SECRET"), }) if err != nil { panic(err) } fmt.Println(token.AccessToken, token.Scope) ``` ##### Agent delegation (RFC 8693 token exchange) An agent acting on behalf of a signed-in user exchanges the user's token plus its own machine token for a delegated token. The original user stays the JWT `sub`; each hop narrows `scope` and appends to the nested `act` claim (re-widening scope is rejected): ```go import "github.com/authorizerdev/authorizer-go/v2" agent, err := authorizer.NewAuthorizerClient( "AGENT_CLIENT_ID", "https://your-instance.authorizer.dev", "https://your-app.example.com", nil, ) if err != nil { panic(err) } // 1. the agent authenticates as itself machineToken, err := agent.GetToken(&authorizer.GetTokenRequest{ GrantType: stringPtr(authorizer.GrantTypeClientCredentials), ClientSecret: stringPtr("AGENT_CLIENT_SECRET"), }) if err != nil { panic(err) } // 2. exchange the user's token for one delegated to this agent, scoped down delegated, err := agent.GetToken(&authorizer.GetTokenRequest{ GrantType: stringPtr(authorizer.GrantTypeTokenExchange), ClientSecret: stringPtr("AGENT_CLIENT_SECRET"), SubjectToken: &userAccessToken, SubjectTokenType: stringPtr("urn:ietf:params:oauth:token-type:access_token"), ActorToken: machineToken.AccessToken, ActorTokenType: stringPtr("urn:ietf:params:oauth:token-type:access_token"), Scope: stringPtr("crm:read"), Resource: stringPtr("https://crm.internal.example"), }) if err != nil { panic(err) } fmt.Println(delegated.AccessToken) // sub is still the user; act.sub is the agent ``` #### Escape hatch — raw GraphQL For any operation not covered by a typed helper: ```go res, err := client.ExecuteGraphQL(&authorizer.GraphQLRequest{ Query: `query { meta { version } }`, Variables: nil, }) if err != nil { panic(err) } ``` `ExecuteGraphQL(req *GraphQLRequest) (map[string]interface{}, error)` returns the parsed response data. ### Examples #### Sign up ```go import "github.com/authorizerdev/authorizer-go/v2" client, err := authorizer.NewAuthorizerClient( "YOUR_CLIENT_ID", "https://your-instance.authorizer.dev", "https://your-app.example.com", nil, ) if err != nil { panic(err) } token, err := client.SignUp(&authorizer.SignUpRequest{ Email: stringPtr("user@example.com"), Password: "Abc@123", ConfirmPassword: "Abc@123", GivenName: stringPtr("Ada"), FamilyName: stringPtr("Lovelace"), }) if err != nil { panic(err) } fmt.Println(token.Message, *token.AccessToken) ``` #### Log in and read the profile ```go import "github.com/authorizerdev/authorizer-go/v2" client, err := authorizer.NewAuthorizerClient( "YOUR_CLIENT_ID", "https://your-instance.authorizer.dev", "https://your-app.example.com", nil, ) if err != nil { panic(err) } token, err := client.Login(&authorizer.LoginRequest{ Email: stringPtr("user@example.com"), Password: "Abc@123", }) if err != nil { panic(err) } headers := map[string]string{"Authorization": "Bearer " + *token.AccessToken} user, err := client.GetProfile(headers) if err != nil { panic(err) } fmt.Println(user.ID, user.Email, user.Roles) ``` #### Validate a JWT ```go import "github.com/authorizerdev/authorizer-go/v2" client, err := authorizer.NewAuthorizerClient( "YOUR_CLIENT_ID", "https://your-instance.authorizer.dev", "https://your-app.example.com", nil, ) if err != nil { panic(err) } res, err := client.ValidateJWTToken(&authorizer.ValidateJWTTokenRequest{ TokenType: authorizer.TokenTypeAccessToken, Token: accessToken, }) if err != nil { panic(err) } fmt.Println(res.IsValid, res.Claims) ``` #### Magic-link login ```go import "github.com/authorizerdev/authorizer-go/v2" client, err := authorizer.NewAuthorizerClient( "YOUR_CLIENT_ID", "https://your-instance.authorizer.dev", "https://your-app.example.com", nil, ) if err != nil { panic(err) } res, err := client.MagicLinkLogin(&authorizer.MagicLinkLoginRequest{ Email: stringPtr("user@example.com"), }) if err != nil { panic(err) } fmt.Println(res.Message) // "Please check your inbox!..." ``` ### Request types All request structs are serializable to JSON via `json.Marshal()`. Fields shown as `*Type` are optional (pointers). | Type | Key fields | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `LoginRequest` | `Password`, `Email`, `PhoneNumber`, `Roles`, `Scope`, `State` | | `SignUpRequest` | `Password`, `ConfirmPassword`, `Email`, `GivenName`, `FamilyName`, `PhoneNumber`, `Roles`, `Scope`, `RedirectURI`, `AppData`, … | | `MagicLinkLoginRequest` | `Email`, `Roles`, `Scope`, `State`, `RedirectURI` | | `VerifyOTPRequest` | `OTP`, `Email`, `PhoneNumber`, `IsTotp`, `State` | | `VerifyEmailRequest` | `Token`, `State` | | `ResendOTPRequest` | `Email`, `PhoneNumber`, `State` | | `ResendVerifyEmailRequest` | `Email` | | `ForgotPasswordRequest` | `Email`, `PhoneNumber`, `State`, `RedirectURI` | | `ResetPasswordRequest` | `Password`, `ConfirmPassword`, `Token`, `OTP`, `PhoneNumber` | | `ValidateJWTTokenRequest` | `TokenType` (required: `TokenTypeAccessToken`, `TokenTypeIDToken` or `TokenTypeRefreshToken`; must match the token's own `token_type` claim), `Token`, `Roles` | | `ValidateSessionRequest` | `Cookie`, `Roles` | | `UpdateProfileRequest` | `Email`, `OldPassword`, `NewPassword`, `ConfirmNewPassword`, `GivenName`, `FamilyName`, `Roles`, `AppData`, … | | `GetTokenRequest` | `Code`, `GrantType`, `RefreshToken`, `CodeVerifier`, `ClientSecret`, `Scope`, `ClientAssertion`, `ClientAssertionType`, `SubjectToken`, `SubjectTokenType`, `ActorToken`, `ActorTokenType`, `Resource` | | `RevokeTokenRequest` | `RefreshToken` | | `RevokeRequest` | `RefreshToken` | | `CheckPermissionsRequest` | `Checks`, `User` | | `ListPermissionsRequest` | `Relation`, `ObjectType`, `User` | | `PermissionCheckInput` | `Relation`, `Object`, `ContextualTuples` | | `FgaTupleInput` | `User`, `Relation`, `Object` | | `SkipMfaSetupRequest` | `Email`, `PhoneNumber`, `State` | | `LockMfaRequest` | `Email`, `PhoneNumber` | | `EmailOtpMfaSetupRequest` | `Email`, `PhoneNumber` | | `SmsOtpMfaSetupRequest` | `Email`, `PhoneNumber` | | `TotpMfaSetupRequest` | `Email`, `PhoneNumber` | | `WebauthnRegistrationOptionsRequest` | `Email`, `PhoneNumber` | | `WebauthnRegistrationVerifyRequest` | `Credential`, `Name`, `Email`, `PhoneNumber`, `State` | | `WebauthnLoginVerifyRequest` | `Credential`, `State` | | `WebauthnDeleteCredentialRequest` | `ID` | ### Response types All response structs are deserializable from JSON via `json.Unmarshal()`. | Type | Key fields | | -------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `AuthTokenResponse` | `Message`, `AccessToken`, `ExpiresIn`, `IdToken`, `RefreshToken`, `ShouldShowEmailOtpScreen`, `ShouldShowMobileOtpScreen`, `ShouldShowTotpScreen`, `ShouldOfferWebauthnMfaSetup`, `ShouldOfferWebauthnMfaVerify`, `ShouldOfferEmailOtpMfaSetup`, `ShouldOfferSmsOtpMfaSetup`, `AuthenticatorScannerImage`, `AuthenticatorSecret`, `AuthenticatorRecoveryCodes`, `User` | | `User` | `ID`, `Email`, `EmailVerified`, `GivenName`, `FamilyName`, `PhoneNumber`, `Roles`, `CreatedAt`, `UpdatedAt`, `IsMultiFactorAuthEnabled`, `HasSkippedMfaSetupAt`, `MfaLockedAt`, `EnrolledMfaMethods`, `AppData`, … | | `Response` | `Message` | | `ForgotPasswordResponse` | `Message`, `ShouldShowMobileOtpScreen` | | `ValidateJWTTokenResponse` | `IsValid`, `Claims` | | `ValidateSessionResponse` | `IsValid`, `User` | | `MetaData` | `Version`, `ClientID`, and `Is*Enabled` feature flags (login providers, MFA, sign-up, etc.) | | `TokenResponse` | `AccessToken`, `ExpiresIn`, `IdToken`, `RefreshToken`, `TokenType`, `Scope`, `IssuedTokenType` | | `CheckPermissionsResponse` | `Results` | | `PermissionCheckResult` | `Relation`, `Object`, `Allowed` | | `ListPermissionsResponse` | `Objects`, `Permissions`, `Truncated` | | `Permission` | `Object`, `Relation` | | `WebauthnRegistrationOptionsResponse` | `Options` (JSON-encoded `PublicKeyCredentialCreationOptions`) | | `WebauthnLoginOptionsResponse` | `Options` (JSON-encoded `PublicKeyCredentialRequestOptions`) | | `WebauthnCredentialInfo` | `ID`, `Name`, `Transports`, `CreatedAt`, `UpdatedAt`, `LastUsedAt` | ### Constants | Constant | Value | | ---------------------------------- | --------------------------------------------------------------- | | `GrantTypeAuthorizationCode` | `"authorization_code"` | | `GrantTypeRefreshToken` | `"refresh_token"` | | `GrantTypeClientCredentials` | `"client_credentials"` | | `GrantTypeTokenExchange` | `"urn:ietf:params:oauth:grant-type:token-exchange"` (RFC 8693) | ### Error handling The SDK returns standard Go errors. Most API errors come back as error messages: ```go import "github.com/authorizerdev/authorizer-go/v2" client, err := authorizer.NewAuthorizerClient( "YOUR_CLIENT_ID", "https://your-instance.authorizer.dev", "https://your-app.example.com", nil, ) if err != nil { panic(err) } token, err := client.Login(&authorizer.LoginRequest{ Email: stringPtr("user@example.com"), Password: "wrong", }) if err != nil { // err will be non-nil fmt.Println(err) } ``` ### Protocol selection By default, the client uses GraphQL. You can override this with `WithProtocol`: ```go import "github.com/authorizerdev/authorizer-go/v2" // Use REST endpoints client, err := authorizer.NewAuthorizerClient( "YOUR_CLIENT_ID", "https://your-instance.authorizer.dev", "https://your-app.example.com", nil, authorizer.WithProtocol(authorizer.ProtocolREST), ) // Use gRPC (requires a separate gRPC endpoint, default 9091) client, err = authorizer.NewAuthorizerClient( "YOUR_CLIENT_ID", "https://your-instance.authorizer.dev", "https://your-app.example.com", nil, authorizer.WithProtocol(authorizer.ProtocolGRPC), authorizer.WithGRPCEndpoint("your-instance.authorizer.dev:9091"), ) ``` ### Utility helpers The SDK exports pointer constructor helpers for optional fields: ```go import "github.com/authorizerdev/authorizer-go/v2" // stringPtr(s) returns a *string pointing to s // intPtr(i) returns an *int64 pointing to i // boolPtr(b) returns a *bool pointing to b email := authorizer.stringPtr("user@example.com") ``` --- ## Getting Started (3) ### Official Documentation For detailed explanation of each function, check the authorizer-go [pkg.go.dev docs](https://pkg.go.dev/github.com/authorizerdev/authorizer-go/v2). **Prerequisite**: You need an Authorizer instance running. See the [deployment guides](../../deployment/) for setup options. ### Authorizer v2 Compatibility The authorizer-go SDK works with both Authorizer v1 and v2 servers. When using with v2: - Obtain the `Client ID` from your v2 server's `--client-id` flag (set at startup) - The SDK methods remain the same; only the server configuration model has changed ### Installation #### Step 1: Install authorizer-go SDK ```bash go get github.com/authorizerdev/authorizer-go/v2 ``` #### Step 2: Initialize authorizer client **Parameters** | Key | Type | Required | Description | | --------------- | ------------------- | -------- | --------------------------------------------------------------------------------------------------------------- | | `clientID` | `string` | `true` | Your unique client identifier (from `--client-id` flag in v2, or dashboard in v1) | | `authorizerURL` | `string` | `true` | Authorizer server URL | | `redirectURL` | `string` | `false` | Default URL to redirect the user after successful signup / login / forgot password | | `extraHeaders` | `map[string]string` | `false` | Set of headers to pass with each request | **Example** ```go defaultHeaders := map[string]string{} authorizerClient, err := authorizer.NewAuthorizerClient("YOUR_CLIENT_ID", "YOUR_AUTHORIZER_URL", "OPTIONAL_REDIRECT_URL", defaultHeaders) if err != nil { panic(err) } ``` #### Step 3: Use SDK methods **Example: Login** ```go response, err := authorizerClient.Login(&authorizer.LoginRequest{ Email: authorizer.NewStringRef("test@yopmail.com"), Password: "Abc@123", }) if err != nil { panic(err) } ``` > `Email` (and `PhoneNumber`) are `*string` fields, so pass a pointer: use the SDK's `authorizer.NewStringRef(v string) *string` helper, or take the address of a local variable. **Example: Validate JWT Token** ```go res, err := authorizerClient.ValidateJWTToken(&authorizer.ValidateJWTTokenRequest{ TokenType: authorizer.TokenTypeIDToken, Token: "your-jwt-token", }) if err != nil { panic(err) } if res.IsValid { // Token is valid } ``` #### Step 4: Fine-grained authorization (FGA) Authorizer ships with an embedded [OpenFGA](https://openfga.dev) relationship-based authorization (ReBAC) engine. The SDK exposes two client-facing methods to query it. Each takes a request struct and a `headers map[string]string` (pass `Authorization: Bearer `). For complete worked scenarios — Go HTTP middleware, list filtering, and tuple lifecycle — see [Authorization recipes](/core/authorization#9-real-world-recipes). **CheckPermissions** -- evaluate one or more permission checks in a single call. `Results` come back in the same order as `Checks` and echo each pair. ```go res, err := authorizerClient.CheckPermissions(&authorizer.CheckPermissionsRequest{ Checks: []*authorizer.PermissionCheckInput{ {Relation: "can_view", Object: "document:1"}, {Relation: "can_edit", Object: "document:1"}, }, }, map[string]string{ "Authorization": "Bearer " + token, }) if err != nil { panic(err) } if res.Results[0].Allowed { // caller may view document:1 } // Each result echoes its pair, so batch responses are self-describing: for _, r := range res.Results { fmt.Printf("%s on %s: %v\n", r.Relation, r.Object, r.Allowed) } ``` The subject defaults to the caller's token. An optional `User` ("type:id", bare id treated as `user:`) is honored only for super-admins or when it equals the caller's own subject. Each check also accepts optional `ContextualTuples` -- extra relationship tuples evaluated for that call only and never persisted, handy for "what-if" checks or request-time facts: ```go res, err := authorizerClient.CheckPermissions(&authorizer.CheckPermissionsRequest{ Checks: []*authorizer.PermissionCheckInput{ { Relation: "can_view", Object: "document:1", ContextualTuples: []*authorizer.FgaTupleInput{ {User: "user:1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", Relation: "viewer", Object: "document:1"}, }, }, }, }, map[string]string{ "Authorization": "Bearer " + token, }) ``` **ListPermissions** -- list what the subject can access. With both `Relation` and `ObjectType` set it answers "which `ObjectType`s can I `Relation`?"; either or both filters may be omitted, so an empty request returns every permission the subject holds. Returns the distinct `Objects`, the `(Object, Relation)` detail in `Permissions`, and `Truncated` (`true` when the result was capped at 1000 entries). ```go res, err := authorizerClient.ListPermissions(&authorizer.ListPermissionsRequest{ Relation: "can_view", ObjectType: "document", }, map[string]string{ "Authorization": "Bearer " + token, }) // res.Objects => ["document:1", "document:7", ...] // No filters: everything the caller holds, with per-relation detail all, err := authorizerClient.ListPermissions(&authorizer.ListPermissionsRequest{}, map[string]string{ "Authorization": "Bearer " + token, }) // all.Permissions => [{Object: "document:1", Relation: "can_view"}, ...] // all.Truncated => false ``` ### Available Methods The SDK provides the following methods: - `Login` -- Authenticate with email and password - `SignUp` -- Register a new user - `VerifyEmail` -- Verify user email - `ForgotPassword` -- Initiate forgot password flow - `ResetPassword` -- Reset password with token - `GetProfile` -- Get user profile - `UpdateProfile` -- Update user profile - `MagicLinkLogin` -- Login with magic link - `ValidateJWTToken` -- Validate a JWT token - `GetSession` -- Get current session - `RevokeToken` -- Revoke a token (`/oauth/revoke`) - `Revoke` -- Revoke a token over the client's selected protocol (graphql/rest/grpc) - `Logout` -- Logout user - `ValidateSession` -- Validate a session - `CheckPermissions` -- Evaluate one or more permission checks (FGA) - `ListPermissions` -- List objects the subject holds a permission on (FGA) - `GetMetaData` -- Get server metadata / enabled feature flags - `GetToken` -- Exchange a grant (`authorization_code`, `refresh_token`, `client_credentials`, or [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) `token-exchange`) for a token at `/oauth/token` -- covers M2M and workload-identity flows - `ExecuteGraphQL` -- Run a raw GraphQL request against the instance - `ResendOTP` -- Resend a one-time code - `ResendVerifyEmail` -- Resend the email verification link - `VerifyOTP` -- Verify a one-time code and complete login - `LockMfa` -- Lock the account into required MFA setup when no verified fallback is enrolled - `SkipMfaSetup` -- Skip optional MFA setup and issue the withheld access token - `EmailOtpMfaSetup` -- Start email-OTP MFA enrollment - `SmsOtpMfaSetup` -- Start SMS-OTP MFA enrollment - `TotpMfaSetup` -- Start [TOTP](https://datatracker.ietf.org/doc/html/rfc6238) MFA enrollment - `DeactivateAccount` -- Deactivate the authenticated user's own account - `WebauthnRegistrationOptions` -- Get a passkey creation challenge - `WebauthnRegistrationVerify` -- Complete passkey enrollment - `WebauthnLoginOptions` -- Get a passkey assertion challenge (email optional, for usernameless login) - `WebauthnLoginVerify` -- Complete passkey login - `WebauthnCredentials` -- List the caller's own registered passkeys - `WebauthnDeleteCredential` -- Delete one of the caller's own registered passkeys --- ## Protocols & Admin API (Authorizer-js) _Added in `@authorizerdev/authorizer-js` for Authorizer **2.3.0-rc.9**._ ### Protocol selection The `Authorizer` client can talk to the server over two wire protocols. **`graphql` is the default** and is 100% backward compatible — existing code keeps working unchanged. | `protocol` | Transport | Notes | | ---------- | ------------------------------- | ------------------------------- | | `'graphql'`| `POST /graphql` | Default. | | `'rest'` | Typed `POST/GET /v1/...` routes | Same flat responses as GraphQL. | > **No gRPC in JS.** Browsers cannot speak raw gRPC. Passing `protocol: 'grpc'` throws a > clear error at construction time. Use the [Go](../authorizer-go/admin) or > [Python](../authorizer-python/admin) SDKs for gRPC. As of 2.3.0-rc.9 all public methods work over both protocols, and both return **identical flat response shapes**. ```js import { Authorizer } from '@authorizerdev/authorizer-js' const authRef = new Authorizer({ authorizerURL: 'YOUR_AUTHORIZER_URL', redirectURL: window.location.origin, clientID: 'YOUR_CLIENT_ID', protocol: 'rest', // 'graphql' (default) | 'rest' }) await authRef.login({ email: 'user@example.com', password: 'Abc@123' }) ``` > OAuth endpoints (`/oauth/token`, `/oauth/revoke`) always use REST regardless of the > selected protocol. ### Admin client The admin API is a **separate client**, `AuthorizerAdmin`, constructed with the admin secret (the value of `--admin-secret`). Admin auth is sent on every call as the `x-authorizer-admin-secret` header. > Keep the admin secret on the **server side** — never ship it to a browser bundle. ```js import { AuthorizerAdmin } from '@authorizerdev/authorizer-js' const admin = new AuthorizerAdmin({ authorizerURL: 'https://your-instance.authorizer.dev', adminSecret: 'YOUR_ADMIN_SECRET', protocol: 'graphql', // 'graphql' (default) | 'rest' }) // List users const { data, errors } = await admin.users() if (!errors?.length) { data.users.forEach((u) => console.log(u.email)) } ``` #### Config | Key | Description | | --------------- | ------------------------------------------------------------- | | `authorizerURL` | Base URL of your Authorizer instance. | | `adminSecret` | Value of `--admin-secret`, sent as `x-authorizer-admin-secret`.| | `protocol` | `'graphql'` (default) or `'rest'`. gRPC is not supported. | #### Admin methods Each method declares which protocols support it. Calling a method on an unsupported protocol returns a clear error rather than emitting a 404. > **⚠ Destructive:** `deleteUser`, `deleteWebhook`, `deleteEmailTemplate`, > `fgaWriteModel` (overwrites the model), `fgaDeleteTuples`, `fgaReset` (wipes all FGA > data), `deleteClient`, `rotateClientSecret` (invalidates the old secret immediately), > `deleteTrustedIssuer`, `deleteOrganization`, `removeOrgMember`, `deleteOrgOIDCConnection`, > `deleteOrgSAMLConnection`, `deleteSAMLServiceProvider`, `retireSAMLIDPKey`, > `deleteScimEndpoint`, `rotateScimToken` (invalidates the old token immediately), and > `deleteOrgDomain` permanently change, remove, or invalidate data. > **Pagination shape:** the paginated list methods (`users`, `verificationRequests`, > `webhooks`, `webhookLogs`, `emailTemplates`, `auditLogs`, `clients`, `trustedIssuers`, > `organizations`, `orgMembers`, `userOrganizations`, `listSAMLServiceProviders`, > `orgDomains`, …) take pagination fields (`limit`, `page`) directly on the params object — > e.g. `admin.webhooks({ limit: 10 })`. There is no `pagination` wrapper. If you have older > code written as `admin.webhooks({ pagination: { limit: 10 } })`, drop the wrapper. ##### Auth, session & meta | Method | Description | rest | gql | | -------------- | ---------------------------------------- | :--: | :-: | | `adminLogin` | Exchange the admin secret for a session. | ✓ | ✓ | | `adminLogout` | End the admin session. | ✓ | ✓ | | `adminSession` | Get the current admin session. | ✓ | ✓ | | `adminMeta` | Server metadata / feature flags. | ✓ | ✓ | ##### Users & access | Method | Description | rest | gql | | ---------------------- | ----------------------------------- | :--: | :-: | | `users` | List users (paginated). | ✓ | ✓ | | `user` | Get a single user. | ✓ | ✓ | | `updateUser` | Update a user. | ✓ | ✓ | | `deleteUser` | **Delete a user.** | ✓ | ✓ | | `verificationRequests` | List pending verification requests. | ✓ | ✓ | | `revokeAccess` | Revoke a user's access. | ✓ | ✓ | | `enableAccess` | Re-enable a user's access. | ✓ | ✓ | | `inviteMembers` | Invite members by email. | ✓ | ✓ | ##### Webhooks | Method | Description | rest | gql | | --------------- | -------------------------------- | :--: | :-: | | `addWebhook` | Create a webhook. | ✓ | ✓ | | `updateWebhook` | Update a webhook. | ✓ | ✓ | | `deleteWebhook` | **Delete a webhook.** | ✓ | ✓ | | `getWebhook` | Get a single webhook. | ✓ | ✓ | | `webhooks` | List webhooks. | ✓ | ✓ | | `webhookLogs` | List webhook delivery logs. | ✓ | ✓ | | `testEndpoint` | Send a test event to a webhook. | ✓ | ✓ | ##### Email templates | Method | Description | rest | gql | | --------------------- | ---------------------------- | :--: | :-: | | `addEmailTemplate` | Create an email template. | ✓ | ✓ | | `updateEmailTemplate` | Update an email template. | ✓ | ✓ | | `deleteEmailTemplate` | **Delete an email template.**| ✓ | ✓ | | `emailTemplates` | List email templates. | ✓ | ✓ | ##### Audit | Method | Description | rest | gql | | ----------- | ----------------- | :--: | :-: | | `auditLogs` | List audit logs. | ✓ | ✓ | ##### FGA admin | Method | Description | rest | gql | | ----------------- | ---------------------------------------- | :--: | :-: | | `fgaGetModel` | Get the current FGA model. | ✓ | ✓ | | `fgaWriteModel` | **Write/overwrite the FGA model.** | ✓ | ✓ | | `fgaWriteTuples` | Write relationship tuples. | ✓ | ✓ | | `fgaDeleteTuples` | **Delete relationship tuples.** | ✓ | ✓ | | `fgaReadTuples` | Read relationship tuples. | ✓ | ✓ | | `fgaListUsers` | List users with a relation to an object. | ✓ | ✓ | | `fgaExpand` | Expand a relation into its userset. | ✓ | ✓ | | `fgaReset` | **Reset all FGA data.** | ✓ | ✓ | ##### OAuth clients (service accounts / M2M) Since 4.2.0 these return `backchannel_token_delivery_mode` (`"poll"` when the client may use [CIBA](../../enterprise/ciba)), and `createClient`/`updateClient` accept it. That field needs **server 2.5.0+**: against an older server, every client method fails over GraphQL with *Cannot query field*. Upgrade the server, or stay on 4.1.x. Registered OAuth clients used by the `client_credentials` and [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) token-exchange grants (see [`getToken`](/sdks/authorizer-js/functions#--gettoken)). `client_secret` is returned exactly once, at creation and at rotation, and is never projected back afterwards. | Method | Description | rest | gql | | ----------------------- | ---------------------------------------------------------- | :--: | :-: | | `createClient` | Register a new OAuth client / service account. | ✓ | ✓ | | `updateClient` | Update a client's name, description, scopes, or active state. | ✓ | ✓ | | `deleteClient` | **Delete a client.** | ✓ | ✓ | | `rotateClientSecret` | **Mint a fresh secret; the old one stops working immediately.** | ✓ | ✓ | | `client` | Get a single client by id (never includes the secret). | ✓ | ✓ | | `clients` | List clients (paginated). | ✓ | ✓ | ##### Trusted issuers (secretless client authentication) External token issuers trusted to authenticate a service account via [RFC 7523](https://datatracker.ietf.org/doc/html/rfc7523) `client_assertion` (Kubernetes SA tokens, [SPIFFE](https://spiffe.io) JWT-SVIDs, cloud OIDC tokens) instead of a shared secret. | Method | Description | rest | gql | | ------------------------- | ------------------------------------------------------------ | :--: | :-: | | `addTrustedIssuer` | Register a trusted issuer for a service account. | ✓ | ✓ | | `updateTrustedIssuer` | Update an existing trusted issuer. | ✓ | ✓ | | `deleteTrustedIssuer` | **Delete a trusted issuer; its tokens stop authenticating immediately.** | ✓ | ✓ | | `trustedIssuer` | Get a single trusted issuer by id. | ✓ | ✓ | | `trustedIssuers` | List trusted issuers, optionally filtered by service account (paginated). | ✓ | ✓ | ##### Organizations Tenant grouping of users. Organizations, their SSO connections, SCIM endpoints, and verified domains gained REST routes in server 2.4.0; on older servers these are GraphQL only. | Method | Description | rest | gql | | --------------------- | ------------------------------------------------------------ | :--: | :-: | | `createOrganization` | Create a new organization. | ✓ | ✓ | | `updateOrganization` | Update an existing organization. | ✓ | ✓ | | `deleteOrganization` | **Delete an organization.** | ✓ | ✓ | | `organization` | Get a single organization by id. | ✓ | ✓ | | `organizations` | List organizations (paginated). | ✓ | ✓ | | `addOrgMember` | Add a user to an organization with optional per-org roles. | ✓ | ✓ | | `removeOrgMember` | **Remove a user from an organization.** | ✓ | ✓ | | `orgMembers` | List an organization's members (paginated). | ✓ | ✓ | | `userOrganizations` | List the organizations a user belongs to, with roles per org (paginated). | ✓ | ✓ | ##### Org SSO connections Per-organization upstream identity providers. `createOrgOIDCConnection` brokers Authorizer as an OIDC Relying Party; `createOrgSAMLConnection` brokers Authorizer as a [SAML 2.0](https://www.oasis-open.org/standard/saml/) Service Provider. Upstream secrets/certificates are accepted on write but never projected back. | Method | Description | rest | gql | | ------------------------------ | ----------------------------------------------------------------------- | :--: | :-: | | `createOrgOIDCConnection` | Create a per-org upstream OIDC connection. | ✓ | ✓ | | `updateOrgOIDCConnection` | Update a per-org upstream OIDC connection. | ✓ | ✓ | | `deleteOrgOIDCConnection` | **Delete a per-org upstream OIDC connection; SSO stops immediately.** | ✓ | ✓ | | `orgOIDCConnection` | Get a connection by id OR by org_id (supply exactly one). | ✓ | ✓ | | `createOrgSAMLConnection` | Create a per-org upstream SAML connection. | ✓ | ✓ | | `updateOrgSAMLConnection` | Update a per-org upstream SAML connection. | ✓ | ✓ | | `deleteOrgSAMLConnection` | **Delete a per-org upstream SAML connection; SSO stops immediately.** | ✓ | ✓ | | `orgSAMLConnection` | Get a connection by id OR by org_id (supply exactly one). | ✓ | ✓ | ##### SAML IdP (Authorizer as Identity Provider) The inverse of the org SAML connection above: downstream Service Providers that Authorizer issues signed SAML assertions to, plus the per-org IdP signing keypairs used to sign them. | Method | Description | rest | gql | | ---------------------------------- | -------------------------------------------------------------------------- | :--: | :-: | | `createSAMLServiceProvider` | Register a downstream SP. | ✓ | ✓ | | `updateSAMLServiceProvider` | Update a downstream SP's name, endpoints, certificate, mapping, or state. | ✓ | ✓ | | `deleteSAMLServiceProvider` | **Delete a downstream SP; SSO for that SP stops immediately.** | ✓ | ✓ | | `samlServiceProvider` | Get a single downstream SP by id. | ✓ | ✓ | | `listSAMLServiceProviders` | List downstream SPs for an org (paginated). | ✓ | ✓ | | `rotateSAMLIDPCert` | Generate a new current signing keypair for an org's SAML IdP. | ✓ | ✓ | | `retireSAMLIDPKey` | **Retire a published-but-superseded key (cannot retire the current key).** | ✓ | ✓ | | `listSAMLIDPKeys` | List all SAML IdP signing keys for an org (unpaginated). | ✓ | ✓ | | `importSAMLSPMetadata` | Parse pasted SP metadata XML into entity_id/acs_url/certificate (does not create a record). | ✓ | ✓ | ##### SCIM endpoints Per-org inbound [SCIM 2.0](https://datatracker.ietf.org/doc/html/rfc7644) provisioning credential. The bearer token is returned exactly once, at creation and at rotation, and is never projected back afterwards. | Method | Description | rest | gql | | ------------------------ | ---------------------------------------------------------------------- | :--: | :-: | | `createScimEndpoint` | Provision the org's inbound SCIM endpoint. | ✓ | ✓ | | `rotateScimToken` | **Mint a fresh bearer token; the old one stops working immediately.** | ✓ | ✓ | | `deleteScimEndpoint` | **Remove the org's SCIM endpoint; inbound provisioning stops immediately.** | ✓ | ✓ | | `scimEndpoint` | Get the org's SCIM endpoint (never includes the token). | ✓ | ✓ | ##### Org verified domains Verified DNS-domain-to-organization mappings used for home-realm discovery. | Method | Description | rest | gql | | --------------------------| --------------------------------------------------------------------------| :--: | :-: | | `requestOrgDomain` | Start domain verification, returning the DNS TXT challenge to publish. | ✓ | ✓ | | `verifyOrgDomain` | Check the published DNS challenge and record the verified domain. | ✓ | ✓ | | `addVerifiedOrgDomain` | Record a verified domain without a DNS challenge (super-admin only). | ✓ | ✓ | | `deleteOrgDomain` | **Remove a verified domain; home-realm discovery for it stops immediately.** | ✓ | ✓ | | `orgDomains` | List an organization's verified domains (paginated). | ✓ | ✓ | ##### OAuth clients (service accounts / M2M) Since 4.2.0 these return `backchannel_token_delivery_mode` (`"poll"` when the client may use [CIBA](../../enterprise/ciba)), and `createClient`/`updateClient` accept it. That field needs **server 2.5.0+**: against an older server, every client method fails over GraphQL with *Cannot query field*. Upgrade the server, or stay on 4.1.x. Registered OAuth clients used by the `client_credentials` and RFC 8693 token-exchange grants (see [`getToken`](/sdks/authorizer-js/functions#--gettoken)). `client_secret` is returned exactly once, at creation and at rotation, and is never projected back afterwards. | Method | Description | rest | gql | | ----------------------- | ---------------------------------------------------------- | :--: | :-: | | `createClient` | Register a new OAuth client / service account. | ✓ | ✓ | | `updateClient` | Update a client's name, description, scopes, or active state. | ✓ | ✓ | | `deleteClient` | **Delete a client.** | ✓ | ✓ | | `rotateClientSecret` | **Mint a fresh secret; the old one stops working immediately.** | ✓ | ✓ | | `client` | Get a single client by id (never includes the secret). | ✓ | ✓ | | `clients` | List clients (paginated). | ✓ | ✓ | ##### Trusted issuers (secretless client authentication) External token issuers trusted to authenticate a service account via RFC 7523 `client_assertion` (Kubernetes SA tokens, SPIFFE JWT-SVIDs, cloud OIDC tokens) instead of a shared secret. | Method | Description | rest | gql | | ------------------------- | ------------------------------------------------------------ | :--: | :-: | | `addTrustedIssuer` | Register a trusted issuer for a service account. | ✓ | ✓ | | `updateTrustedIssuer` | Update an existing trusted issuer. | ✓ | ✓ | | `deleteTrustedIssuer` | **Delete a trusted issuer; its tokens stop authenticating immediately.** | ✓ | ✓ | | `trustedIssuer` | Get a single trusted issuer by id. | ✓ | ✓ | | `trustedIssuers` | List trusted issuers, optionally filtered by service account (paginated). | ✓ | ✓ | ##### Organizations Tenant grouping of users. Organizations, their SSO connections, SCIM endpoints, and verified domains have **no REST/proto routes yet** — GraphQL only. | Method | Description | rest | gql | | --------------------- | ------------------------------------------------------------ | :--: | :-: | | `createOrganization` | Create a new organization. | | ✓ | | `updateOrganization` | Update an existing organization. | | ✓ | | `deleteOrganization` | **Delete an organization.** | | ✓ | | `organization` | Get a single organization by id. | | ✓ | | `organizations` | List organizations (paginated). | | ✓ | | `addOrgMember` | Add a user to an organization with optional per-org roles. | | ✓ | | `removeOrgMember` | **Remove a user from an organization.** | | ✓ | | `orgMembers` | List an organization's members (paginated). | | ✓ | | `userOrganizations` | List the organizations a user belongs to, with roles per org (paginated). | | ✓ | ##### Org SSO connections Per-organization upstream identity providers. `createOrgOIDCConnection` brokers Authorizer as an OIDC Relying Party; `createOrgSAMLConnection` brokers Authorizer as a SAML 2.0 Service Provider. Upstream secrets/certificates are accepted on write but never projected back. GraphQL only. | Method | Description | rest | gql | | ------------------------------ | ----------------------------------------------------------------------- | :--: | :-: | | `createOrgOIDCConnection` | Create a per-org upstream OIDC connection. | | ✓ | | `updateOrgOIDCConnection` | Update a per-org upstream OIDC connection. | | ✓ | | `deleteOrgOIDCConnection` | **Delete a per-org upstream OIDC connection; SSO stops immediately.** | | ✓ | | `orgOIDCConnection` | Get a connection by id OR by org_id (supply exactly one). | | ✓ | | `createOrgSAMLConnection` | Create a per-org upstream SAML connection. | | ✓ | | `updateOrgSAMLConnection` | Update a per-org upstream SAML connection. | | ✓ | | `deleteOrgSAMLConnection` | **Delete a per-org upstream SAML connection; SSO stops immediately.** | | ✓ | | `orgSAMLConnection` | Get a connection by id OR by org_id (supply exactly one). | | ✓ | ##### SAML IdP (Authorizer as Identity Provider) The inverse of the org SAML connection above: downstream Service Providers that Authorizer issues signed SAML assertions to, plus the per-org IdP signing keypairs used to sign them. | Method | Description | rest | gql | | ---------------------------------- | -------------------------------------------------------------------------- | :--: | :-: | | `createSAMLServiceProvider` | Register a downstream SP. | ✓ | ✓ | | `updateSAMLServiceProvider` | Update a downstream SP's name, endpoints, certificate, mapping, or state. | ✓ | ✓ | | `deleteSAMLServiceProvider` | **Delete a downstream SP; SSO for that SP stops immediately.** | ✓ | ✓ | | `samlServiceProvider` | Get a single downstream SP by id. | ✓ | ✓ | | `listSAMLServiceProviders` | List downstream SPs for an org (paginated). | ✓ | ✓ | | `rotateSAMLIDPCert` | Generate a new current signing keypair for an org's SAML IdP. | ✓ | ✓ | | `retireSAMLIDPKey` | **Retire a published-but-superseded key (cannot retire the current key).** | ✓ | ✓ | | `listSAMLIDPKeys` | List all SAML IdP signing keys for an org (unpaginated). | ✓ | ✓ | | `importSAMLSPMetadata` | Parse pasted SP metadata XML into entity_id/acs_url/certificate (does not create a record). | ✓ | ✓ | ##### SCIM endpoints Per-org inbound SCIM 2.0 provisioning credential. The bearer token is returned exactly once, at creation and at rotation, and is never projected back afterwards. GraphQL only. | Method | Description | rest | gql | | ------------------------ | ---------------------------------------------------------------------- | :--: | :-: | | `createScimEndpoint` | Provision the org's inbound SCIM endpoint. | | ✓ | | `rotateScimToken` | **Mint a fresh bearer token; the old one stops working immediately.** | | ✓ | | `deleteScimEndpoint` | **Remove the org's SCIM endpoint; inbound provisioning stops immediately.** | | ✓ | | `scimEndpoint` | Get the org's SCIM endpoint (never includes the token). | | ✓ | ##### Org verified domains Verified DNS-domain-to-organization mappings used for home-realm discovery. GraphQL only. | Method | Description | rest | gql | | --------------------------| --------------------------------------------------------------------------| :--: | :-: | | `requestOrgDomain` | Start domain verification, returning the DNS TXT challenge to publish. | | ✓ | | `verifyOrgDomain` | Check the published DNS challenge and record the verified domain. | | ✓ | | `addVerifiedOrgDomain` | Record a verified domain without a DNS challenge (super-admin only). | | ✓ | | `deleteOrgDomain` | **Remove a verified domain; home-realm discovery for it stops immediately.** | | ✓ | | `orgDomains` | List an organization's verified domains (paginated). | | ✓ | ##### GraphQL-only extras These have no REST equivalent and work **over GraphQL only**: | Method | Description | | ----------------- | ------------------------------------ | | `adminSignup` | Bootstrap the first admin. | | `updateEnv` | **Deprecated server-side** — v2 configures everything via CLI flags; the resolver always errors. | | `generateJWTKeys` | Generate a new JWT signing key pair. | --- ## Functions (Authorizer-js) [`@authorizerdev/authorizer-js`](https://www.npmjs.com/package/@authorizerdev/authorizer-js) SDK comes with bunch of utility functions, that you can use to perform various operations without worrying about the API details. --- **Table of Contents** - [authorize](#--authorize) - [browserLogin](#--browserlogin) - [getToken](#--gettoken) - [requireApproval / requestApproval / pollApproval](#--requireapproval) - [login](#--login) - [signup](#--signup) - [verifyEmail](#--verifyemail) - [resendVerifyEmail](#--resendverifyemail) - [getProfile](#--getprofile) - [updateProfile](#--updateprofile) - [forgotPassword](#--forgotpassword) - [resetPassword](#--resetpassword) - [oauthLogin](#--oauthlogin) - [magicLinkLogin](#--magiclinklogin) - [getMetaData](#--getmetadata) - [getSession](#--getsession) - [revokeToken](#--revoketoken) - [logout](#--logout) - [validateJWTToken](#--validatejwttoken) - [validateSession](#--validatesession) - [checkPermissions](#--checkpermissions) - [listPermissions](#--listpermissions) - [verifyOtp](#--verifyotp) - [resendOtp](#--resendotp) - [deactivateAccount](#--deactivateaccount) - [skipMfaSetup](#--skipmfasetup) - [lockMfa](#--lockmfa) - [emailOtpMfaSetup](#--emailotpmfasetup) - [smsOtpMfaSetup](#--smsotpmfasetup) - [totpMfaSetup](#--totpmfasetup) - [webauthnRegistrationOptions](#--webauthnregistrationoptions) - [webauthnRegistrationVerify](#--webauthnregistrationverify) - [webauthnLoginOptions](#--webauthnloginoptions) - [webauthnLoginVerify](#--webauthnloginverify) - [webauthnCredentials](#--webauthncredentials) - [webauthnDeleteCredential](#--webauthndeletecredential) - [registerPasskey](#--registerpasskey) - [loginWithPasskey](#--loginwithpasskey) - [loginWithPasskeyAutofill](#--loginwithpasskeyautofill) - [cancelPasskeyAutofill](#--cancelpasskeyautofill) - [isWebauthnSupported](#--iswebauthnsupported) - [parseMfaRedirectParams](#--parsemfaredirectparams) These functions can be invoked using the `Authorizer` instance: ```js const authRef = new Authorizer({ authorizerURL: 'YOUR_AUTHORIZER_INSTANCE_URL', redirectURL: window.location.origin, clientID: 'YOUR_CLIENT_ID', }) ``` ### - `authorize` Function to auto login from browser using the builtin UI of `authorizer`. It checks for session, if available returns the token information, else redirects to login page. - It supports [PKCE flow](https://datatracker.ietf.org/doc/html/rfc7636). This will help user to perform authentication and authorization in safe memory and prevent from CSRF attack. It also enables perform authorization with safety on mobile applications (Tried and tested with [Expo AuthSession](https://github.com/authorizerdev/examples/tree/main/with-react-native-expo)) - It supports [Implicit Flow](https://datatracker.ietf.org/doc/html/rfc6749#section-1.3.2) It accepts JSON object as a parameter with following keys | Key | Description | Required | | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `response_type` | What type of response you want. It supports `code` & `token` as response types. Default value is `token` | false | | `response_mode` | Response is required in which format. Supports 2 forms `query` (returns redirect url with response in query string) and `web_message` (returns html page with data embedded in JS). Default its value is `query` | false | | `use_refresh_token` | Whether to include refresh token in response or not | false | If session exists following keys are returned in `data` object. **Response** | Key | Description | | ---------------------- | ------------------------------------------------------------------------------------------------------ | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | **Sample Usage** ```js const { data, errors } = await authRef.authorize({ response_type: 'code', response_mode: 'query', }) ``` ### - `browserLogin` Function to silently check for an existing browser session (via `getSession`) and return its tokens. If no session exists it falls back to redirecting the browser to the hosted login app (`{authorizerURL}/app`), the same fallback `authorize` uses when the iframe check fails. Browser-only; it takes no parameters. **Sample Usage** ```js const { data, errors } = await authRef.browserLogin() if (data?.access_token) { // an existing session was found } ``` ### - `getToken` Function to exchange credentials for tokens at `/oauth/token`. This call always goes over REST regardless of the client's configured `protocol` (see [Protocols & Admin API](/sdks/authorizer-js/admin)). Supports 4 grant types: `authorization_code` (default), `refresh_token`, `client_credentials` ([RFC 6749 §4.4](https://datatracker.ietf.org/doc/html/rfc6749#section-4.4)), and token exchange ([RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693), `urn:ietf:params:oauth:grant-type:token-exchange`). > **Server-side only:** `client_credentials` and token exchange are machine/service flows for trusted server-side code. Never ship `client_secret`, `client_assertion`, or subject/actor tokens in a browser bundle. It accepts JSON object as a parameter with following keys | Key | Description | Required | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------- | -------- | | `grant_type` | `authorization_code`, `refresh_token`, `client_credentials`, or `urn:ietf:params:oauth:grant-type:token-exchange`. Default is `authorization_code` | false | | `code_verifier` | Code verifier to verify against the code_challenge sent in authorize request. Required if `authorization_code` flow is used (handled automatically by the SDK). | false | | `code` | Code returned form authorize request is sent to make sure it is follow up of same request | false | | `refresh_token` | Refresh token used to get the new access token. Required in case of `refresh_token` grant type | false | | `client_secret` | Service-account secret. Used with `client_credentials`. Server-side only. | false | | `scope` | Space-delimited OAuth2 scope. Omit for `client_credentials` to get the service account's full allowed scope set. | false | | `client_assertion` | [RFC 7523](https://datatracker.ietf.org/doc/html/rfc7523) JWT-bearer client credential (secretless workload identity: K8s SA tokens, [SPIFFE](https://spiffe.io) JWT-SVIDs, cloud OIDC tokens). | false | | `client_assertion_type` | Type of `client_assertion`. Use the exported `CLIENT_ASSERTION_TYPE_JWT_BEARER` constant. | false | | `subject_token` | The authority being exercised (the user's token). Required for token exchange. | false | | `subject_token_type` | Type of `subject_token`. Use the exported `TOKEN_TYPE_ACCESS_TOKEN` / `TOKEN_TYPE_JWT` constants. | false | | `actor_token` | The acting agent's token; its presence selects the delegation profile. Used for token exchange. | false | | `actor_token_type` | Type of `actor_token`. | false | | `resource` | RFC 8707 resource indicator the issued token should be audience-bound to. | false | If session exists following keys are returned in the `data` object. **Response** | Key | Description | | ---------------------- | ------------------------------------------------------------------------------------------------------ | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information. Only issued on user grants (`authorization_code` / `refresh_token`) — absent for `client_credentials` and token exchange | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | | `token_type` | Token type, e.g. `Bearer` | | `scope` | Granted scope. Returned by `client_credentials` and token exchange grants | | `issued_token_type` | The token type URN issued. Returned by the token exchange grant ([RFC 8693 §2.2](https://datatracker.ietf.org/doc/html/rfc8693#section-2.2)) | **Sample Usage** ```js // for web apps const { data, errors } = await authRef.getToken({ response_type: 'code', response_mode: 'query', }) // for mobile applications / desktop apps const { data, errors } = await authRef.getToken({ grant_type: 'refresh_token', refresh_token: 'your refresh_token from login (should store in memmory such as store, variables)', }) // server-side machine-to-machine (client_credentials) — never in a browser bundle const { data, errors } = await authRef.getToken({ grant_type: 'client_credentials', client_secret: 'YOUR_CLIENT_SECRET', }) ``` ### - `requireApproval` Server-side only, Authorizer 2.5.0+. An agent's service account (registered for [CIBA](../../enterprise/ciba)) asks a user to approve one action and waits for the answer. `requestApproval` sends the request and `pollApproval` polls once; `requireApproval` does both, polling at the server's interval and adding 5 seconds on `slow_down`. ```js const agent = new Authorizer({ authorizerURL, redirectURL, clientID: AGENT_CLIENT_ID }) const { data, errors } = await agent.requireApproval( { client_secret: AGENT_CLIENT_SECRET, scope: 'openid payments:write', login_hint: userID, // or id_token_hint binding_message: 'Pay $40 to Acme Corp', resource: 'https://api.example.com/payments', authorization_details: [{ type: 'payment_initiation', amount: 40, currency: 'USD' }], }, { signal, onRequested: () => console.log('check your email') }, ) // data: { access_token, id_token, expires_in, scope, authorization_details } // errors[0].code: access_denied | expired_token | invalid_target | ... | aborted ``` At the resource server, after verifying the JWT against `/.well-known/jwks.json`: ```js import { checkApprovedAction } from '@authorizerdev/authorizer-js' const { ok, reason } = await checkApprovedAction(claims, { resource: 'https://api.example.com/payments', agent: AGENT_CLIENT_ID, matchesAuthorizationDetails: (d) => d.some((x) => x.type === 'payment_initiation' && x.amount === amount), }) ``` The token stays valid for 5 minutes; record `claims.ciba.req` until `exp` if the action must happen once. ### - `signup` Function to sign-up user using email and password. It accepts JSON object as a parameter with the following keys | Key | Description | Required | | ------------------ | ------------------------------------------------------------------------------------------------------------- | -------- | | `email` | Email address of user | true | | `password` | Password that user wants to set | true | | `confirm_password` | Value same as password to make sure that its user and not robot | true | | `given_name` | First name of the user | false | | `family_name` | Last name of the user | false | | `picture` | Profile picture URL | false | | `roles` | Array of string with valid roles. Defaults to `[user]` if not configured | false | | `middle_name` | middle name of user | false | | `nickname` | nick name of user | false | | `gender` | gender of user | false | | `birthdate` | birthdate of user | false | | `phone_number` | phone number of user | false | | `redirect_uri` | URL where user should be redirected after login | false | | `scope` | List of openID scopes. If not present default scopes ['openid', 'email', 'profile', 'offline_access'] is used | false | | `state` | Opaque state string round-tripped through the flow. Auto-generated by the SDK if omitted | false | | `app_data` | Arbitrary JSON object of application-specific data stored on the user | false | Following is the response for the `signup` in the `data` object **Response** | Key | Description | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `message` | Success / Error message from server | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | | `user` | User object with its profile keys mentioned [above](#--getprofile). This is only returned if `DISABLE_EMAIL_NOTIFICATION` is set to `true` in environment variables | | `should_show_email_otp_screen` | Is set to true if email based multi factor authentication is enabled | | `should_show_mobile_otp_screen` | Is set to true if mobiled based multi factor authentication is enabled | | `should_show_totp_screen` | Is set to true if totp based multi factor authentication is enabled | | `should_offer_webauthn_mfa_verify` | Is set to true if the user should be offered to verify with an existing passkey as their second factor | | `should_offer_webauthn_mfa_setup` | Is set to true if the user should be offered to enroll a passkey as their second factor | | `should_offer_email_otp_mfa_setup` | Is set to true if the user should be offered email-OTP MFA enrollment | | `should_offer_sms_otp_mfa_setup` | Is set to true if the user should be offered SMS-OTP MFA enrollment | | `authenticator_scanner_image` | If totp registration is pending it sends base64 encoded image string that can be rendered by totp app scanners like Google Authentication | | `authenticator_secret` | If totp registration is pending, then this secret can be used for registration instead of image on authenticator apps | | `authenticator_recovery_codes` | If totp registration is pending, then recovery codes are sent using which totp can be accessed again | **Sample Usage** ```js const { data, errors } = await authRef.signup({ email: 'foo@bar.com', password: 'test', confirm_password: 'test', scope: ['offline_access'], // for refresh token }) ``` ### - `login` Function to login user using email and password. It accepts JSON object as a parameter with the following keys | Key | Description | Required | | ---------- | ---------------------------------------------------------------------------------------------------------------------- | -------- | | `email` | Email address of user | false | | `phone_number` | Phone number of user (alternative to `email`) | false | | `password` | Password of user | true | | `roles` | Roles of user that he/she wants to login with. It accepts array of string. Defaults to `[user]` role if not configured | false | | `scope` | List of openID scopes. If not present default scopes ['openid', 'email', 'profile'] is used | false | | `state` | Opaque state string round-tripped through the flow | false | Either `email` or `phone_number` is required. Following is the response for `login` in the `data` object **Response** | Key | Description | | ---------------------- | ------------------------------------------------------------------------------------------------------ | | `message` | Error / Success message from server | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | | `user` | User object with all the basic profile information | | `should_show_email_otp_screen` | Is set to true if email based multi factor authentication is enabled | | `should_show_mobile_otp_screen` | Is set to true if mobiled based multi factor authentication is enabled | | `should_show_totp_screen` | Is set to true if totp based multi factor authentication is enabled | | `should_offer_webauthn_mfa_verify` | Is set to true if the user should be offered to verify with an existing passkey as their second factor | | `should_offer_webauthn_mfa_setup` | Is set to true if the user should be offered to enroll a passkey as their second factor | | `should_offer_email_otp_mfa_setup` | Is set to true if the user should be offered email-OTP MFA enrollment | | `should_offer_sms_otp_mfa_setup` | Is set to true if the user should be offered SMS-OTP MFA enrollment | | `authenticator_scanner_image` | If totp registration is pending it sends base64 encoded image string that can be rendered by totp app scanners like Google Authentication | | `authenticator_secret` | If totp registration is pending, then this secret can be used for registration instead of image on authenticator apps | | `authenticator_recovery_codes` | If totp registration is pending, then recovery codes are sent using which totp can be accessed again | **Sample Usage** ```js const { data, errors } = await authRef.login({ email: 'foo@bar.com', password: 'test', }) ``` ### - `verifyEmail` Function to verify email address of user when they signup. It accepts JSON object as a parameter with following keys | Key | Description | Required | | ------- | ----------------------------- | -------- | | `token` | Token sent for verifying user | true | | `state` | Opaque state string round-tripped through the flow | false | This mutation returns `AuthResponse` type with the following keys in the `data` object **Response** | Key | Description | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `message` | Success / Error message from server | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | | `user` | User object with its profile keys mentioned [above](#--getprofile). | | `should_show_email_otp_screen` | Is set to true if email based multi factor authentication is enabled | | `should_show_mobile_otp_screen` | Is set to true if mobiled based multi factor authentication is enabled | | `should_show_totp_screen` | Is set to true if totp based multi factor authentication is enabled | | `should_offer_webauthn_mfa_verify` | Is set to true if the user should be offered to verify with an existing passkey as their second factor | | `should_offer_webauthn_mfa_setup` | Is set to true if the user should be offered to enroll a passkey as their second factor | | `should_offer_email_otp_mfa_setup` | Is set to true if the user should be offered email-OTP MFA enrollment | | `should_offer_sms_otp_mfa_setup` | Is set to true if the user should be offered SMS-OTP MFA enrollment | | `authenticator_scanner_image` | If totp registration is pending it sends base64 encoded image string that can be rendered by totp app scanners like Google Authentication | | `authenticator_secret` | If totp registration is pending, then this secret can be used for registration instead of image on authenticator apps | | `authenticator_recovery_codes` | If totp registration is pending, then recovery codes are sent using which totp can be accessed again | **Sample Usage** ```js const { data, errors } = await authRef.verifyEmail({ token: `some_token`, }) ``` ### - `resendVerifyEmail` Function to resend the verification email to a user who signed up but hasn't verified their email yet. It accepts JSON object as a parameter with following keys | Key | Description | Required | | ------------ | --------------------------------------------- | -------- | | `email` | Email address to resend the verification to | true | | `identifier` | Verification identifier (`basic_signup`) | true | | `state` | Opaque state string round-tripped through the flow | false | It returns the following keys in response `data` object **Response** | Key | Description | | --------- | ------------------------------------ | | `message` | Success / Error message from server | **Sample Usage** ```js const { data, errors } = await authRef.resendVerifyEmail({ email: 'foo@bar.com', identifier: 'basic_signup', }) ``` ### - `getProfile` Function to get profile of user. This function makes an authorized request, hence if it is used from the browser the HTTP cookie is sent if user has logged in else you need to pass headers object. It accepts the optional JSON object as parameter, you can pass the HTTP Headers there. | Key | Description | Required | | --------------- | -------------------------------------------------------------------------------------- | -------- | | `Authorization` | Authorization header passed to the server. It needs `Bearer access_token` as its value | true | It returns the following keys in response `data` object **Response** | Key | Description | | -------------------------------- | ------------------------------------------------------------------ | | `id` | user unique identifier | | `email` | email address of user | | `email_verified` | determine if email is verified or not | | `given_name` | first name of user | | `family_name` | last name of user | | `middle_name` | middle name of user | | `nickname` | nick name of user | | `preferred_username` | preferred username of user | | `gender` | gender of user | | `birthdate` | birthdate of user | | `phone_number` | phone number of user | | `phone_number_verified` | determine if phone number is verified or not | | `picture` | profile picture URL | | `signup_methods` | methods using which user have signed up, eg: `google,github` | | `roles` | user roles | | `created_at` | timestamp at which the user entry was created | | `updated_at` | timestamp at which the user entry was updated | | `revoked_timestamp` | timestamp at which access was revoked, if any | | `is_multi_factor_auth_enabled` | whether the user has multi-factor authentication enabled | | `has_skipped_mfa_setup_at` | timestamp at which the user skipped MFA setup, if any | | `mfa_locked_at` | timestamp at which MFA was locked for the user, if any | | `enrolled_mfa_methods` | list of MFA methods the user has enrolled (e.g. `totp`, `webauthn`) | | `app_data` | arbitrary JSON object of application-specific data on the user | **Sample Usage** ```js // from browser if HTTP cookie is present const { data, errors } = await authRef.getProfile() // from NodeJS / if HTTP cookie is not used const { data, errors } = await authRef.getProfile({ Authorization: `Bearer ${token}`, }) ``` ### - `updateProfile` Function to update profile of user. This function makes an authorized request, hence if it is used from the browser the HTTP cookie is sent if user has logged in else you need to pass headers object. It accepts 2 JSON object as its parameters. 1. data - User data that needs to be updated 2. headers - To pass Authorization header Here are the keys that `data` object accepts | Key | Description | Required | | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `given_name` | New first name of the user | false | | `family_name` | New last name of the user | false | | `middle_name` | New middle name of the user | false | | `nickname` | New nickname of the user | false | | `gender` | New gender of the user | false | | `birthdate` | New birthdate of the user | false | | `phone_number` | New phone number of the user | false | | `picture` | New profile picture URL of the user | false | | `email` | New email of th user. This will logout the user and send the new verification mail to user if `DISABLE_EMAIL_NOTIFICATION` is set to false | false | | `old_password` | In case if user wants to change password they need to specify the older password here. In this scenario `new_password` and `confirm_new_password` will be required. | false | | `new_password` | New password that user wants to set. In this scenario `old_password` and `confirm_new_password` will be required | false | | `confirm_new_password` | Value same as the new password to make sure it matches the password entered by user. In this scenario `old_password` and `new_password` will be required | false | | `is_multi_factor_auth_enabled` | Toggle whether MFA is enabled for the user | false | | `app_data` | Arbitrary JSON object of application-specific data stored on the user | false | > Note: earlier versions of this doc referred to these password fields as `newPassword` / `confirmNewPassword` (camelCase) — the SDK and server both expect the snake_case `new_password` / `confirm_new_password` shown above. Here is sample of `headers` object | Key | Description | Required | | --------------- | -------------------------------------------------------------------------------------- | -------- | | `Authorization` | Authorization header passed to the server. It needs `Bearer access_token` as its value | true | It returns the following keys in response `data` object **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Usage** ```js const { data, errors } = await authRef.updateProfile( { given_name: `bob`, }, { Authorization: `Bearer some_token`, }, ) ``` ### - forgotPassword Function that can be used in case if user has forgotten their password. Forgot password is 2 step process. Step 1: Send email to registered user Step 2: Reset password. This function is Step 1 process. It accepts JSON object as parameter with the following keys > Note: You will need a SMTP server with an email address and password configured as [authorizer environment](/core/server-config) using which system can send emails. | Key | Description | Required | | -------------- | ------------------------------------------------------------ | -------- | | `email` | Email for which password needs to be changed | false | | `phone_number` | Phone number for which password needs to be changed (alternative to `email`) | false | | `redirect_uri` | URL where user should be redirected after resetting password. Defaults to the client's configured `redirectURL` | false | | `state` | Opaque state string round-tripped through the flow. Auto-generated by the SDK if omitted | false | Either `email` or `phone_number` is required. It returns the following keys in response `data` object **Response** | Key | Description | | ------------------------------- | --------------------------------------- | | `message` | Success / Error message from server | | `should_show_mobile_otp_screen` | Show OTP screen if mobile login is used | **Sample Usage** ```js const { data, errors } = await authRef.forgotPassword({ email: 'foo@bar.com', }) ``` ### - `resetPassword` Function to reset password. This is the step 2 of forgot password process. It accepts JSON object as a parameter with following keys | Key | Description | Required | | -------------------- | --------------------------------------------------------------------- | -------- | | `token` | Token sent to the user by email in step 1 (`forgotPassword`) | false | | `otp` | OTP sent to the user by SMS in step 1, if mobile-based reset is used | false | | `phone_number` | Phone number the OTP was sent to. Required if `otp` is used | false | | `password` | New password to set | true | | `confirm_password` | Value same as `password` to make sure it matches | true | Either `token` (email flow) or `otp` + `phone_number` (mobile flow) is required, along with `password` and `confirm_password`. It returns the following keys in response `data` object **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Usage** ```js const { data, errors } = await authRef.resetPassword({ token: `some_token`, password: 'newPass123', confirm_password: 'newPass123', }) ``` ### - `oauthLogin` Function to login using OAuth Providers. This is mainly used in browser as user is redirect to respective oauth platform. > Note only enabled oauth providers can be used here. To get the information about enabled oauth provider you can use [`getMetaData`](#--getmetadata) function It accepts the following positional arguments: | Argument | Description | Required | | ------------------ | ----------------------------------------------------------------------------------------------------- | -------- | | `oauthProvider` | One of `apple`, `github`, `google`, `facebook`, `linkedin`, `twitter`, `microsoft`, `twitch`, `roblox`, `discord` | true | | `roles` | Array of role strings to log in with | false | | `redirect_uri` | URL to redirect to after the OAuth flow completes. Defaults to the client's configured `redirectURL` | false | | `state` | Opaque state string round-tripped through the flow. Auto-generated by the SDK if omitted | false | **Sample Usage** ```js await authRef.oauthLogin('google') // login with specific role(s) await authRef.oauthLogin('google', ['admin']) // override the redirect_uri await authRef.oauthLogin('github', undefined, 'https://your-app.example.com/callback') ``` ### - magicLinkLogin Function to perform password less login. > Note: You will need a SMTP server with an email address and password configured as [authorizer environment](/core/server-config) using which system can send emails. | Key | Description | Required | | -------------- | ------------------------------------------------------------------------------------------- | -------- | | `email` | Email using which user needs to login | true | | `roles` | List of valid valid roles using which user needs to login | false | | `scope` | List of openID scopes. If not present default scopes ['openid', 'email', 'profile'] is used | false | | `redirect_uri` | URL where user should be redirected after login | false | | `state` | Opaque state string round-tripped through the flow. Auto-generated by the SDK if omitted | false | It returns the following keys in response `data` object **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Usage** ```js const { data, errors } = await authRef.magicLinkLogin({ email: 'foo@bar.com', }) ``` ### - `getMetaData` Function to get meta information about your authorizer instance. eg, version, configurations, etc It returns the following keys in response `data` object **Response** | Key | Description | | -------------------------------------------- | ----------------------------------------------------------------------- | | `version` | Authorizer version that is currently deployed | | `client_id` | Identifier of your instance | | `is_google_login_enabled` | It gives information if google login is configured or not | | `is_github_login_enabled` | It gives information if github login is configured or not | | `is_facebook_login_enabled` | It gives information if facebook login is configured or not | | `is_linkedin_login_enabled` | It gives information if linkedin login is configured or not | | `is_apple_login_enabled` | It gives information if apple login is configured or not | | `is_discord_login_enabled` | It gives information if discord login is configured or not | | `is_twitter_login_enabled` | It gives information if twitter login is configured or not | | `is_microsoft_login_enabled` | It gives information if microsoft login is configured or not | | `is_twitch_login_enabled` | It gives information if twitch login is configured or not | | `is_roblox_login_enabled` | It gives information if roblox login is configured or not | | `is_email_verification_enabled` | It gives information if email verification is enabled or not | | `is_basic_authentication_enabled` | It gives information, if basic auth is enabled or not | | `is_magic_link_login_enabled` | It gives information if password less login is enabled or not | | `is_sign_up_enabled` | It gives information if new sign ups are allowed | | `is_strong_password_enabled` | It gives information if strong password policy is enforced | | `is_multi_factor_auth_enabled` | It gives information if multi-factor authentication is enabled | | `is_mobile_basic_authentication_enabled` | It gives information if mobile (phone number) basic auth is enabled | | `is_phone_verification_enabled` | It gives information if phone verification is enabled | | `is_totp_mfa_enabled` | It gives information if [TOTP](https://datatracker.ietf.org/doc/html/rfc6238) is available as an MFA method | | `is_email_otp_mfa_enabled` | It gives information if email OTP is available as an MFA method | | `is_sms_otp_mfa_enabled` | It gives information if SMS OTP is available as an MFA method | | `is_webauthn_enabled` | It gives information if [WebAuthn](https://www.w3.org/TR/webauthn-2/)/passkeys are available as an MFA method | | `is_mfa_enforced` | It gives information if MFA is enforced for all users | | `is_org_discovery_enabled` | It gives information if home-realm/org discovery is enabled | **Sample Usage** ```js const { data, errors } = await authRef.getMetaData() ``` ### - `getSession` Function to get session information. This function makes an authorized request, hence if it is used from the browser the HTTP cookie is sent if user has logged in else you need to pass headers object. It accepts the optional JSON object as parameter, you can pass the HTTP Headers there. Optionally you can also pass a `SessionQueryRequest` object (`{ roles?: string[], scope?: string[] }`) as the second argument to validate `roles` / `scope` against the session. | Key | Description | Required | | --------------- | ------------------------------------------------------------------------------------ | -------- | | `Authorization` | Authorization header passed to the server. It needs `Bearer some_token` as its value | false | It returns the following keys in response `data` object **Response** | Key | Description | | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `message` | Error / Success message from server | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | | `user` | User object with all the basic profile information | | `should_show_email_otp_screen` | Is set to true if email based multi factor authentication is enabled | | `should_show_mobile_otp_screen` | Is set to true if mobiled based multi factor authentication is enabled | | `should_show_totp_screen` | Is set to true if totp based multi factor authentication is enabled | | `should_offer_webauthn_mfa_verify` | Is set to true if the user should be offered to verify with an existing passkey as their second factor | | `should_offer_webauthn_mfa_setup` | Is set to true if the user should be offered to enroll a passkey as their second factor | | `should_offer_email_otp_mfa_setup` | Is set to true if the user should be offered email-OTP MFA enrollment | | `should_offer_sms_otp_mfa_setup` | Is set to true if the user should be offered SMS-OTP MFA enrollment | | `authenticator_scanner_image` | If totp registration is pending it sends base64 encoded image string that can be rendered by totp app scanners like Google Authentication | | `authenticator_secret` | If totp registration is pending, then this secret can be used for registration instead of image on authenticator apps | | `authenticator_recovery_codes` | If totp registration is pending, then recovery codes are sent using which totp can be accessed again | **Sample Usage** ```js // from browser with HTTP Cookie const { data, errors } = await authRef.getSession() // role validation with http cookie — the second argument is a SessionQueryRequest object, not a bare string const { data, errors } = await authRef.getSession(null, { roles: ['admin'] }) // from NodeJS / if HTTP cookie is not used const { data, errors } = await authRef.getSession( { Authorization: `Bearer some_token`, }, { roles: ['admin'] }, ) ``` ### - `revokeToken` Function to revoke refresh token. It accepts json object as its parameter with following keys **JSON Object** | Key | Description | Required | | --------------- | --------------------------- | -------- | | `refresh_token` | Refresh token to be revoked | true | It returns the following keys in response `data` object **Response** | Key | Description | | --------- | --------------- | | `message` | Success message | **Sample Usage** ```js const { data, errors } = await authRef.revokeToken({ refresh_token: 'foo', }) ``` ### - `logout` Function to logout user. This function makes an authorized request, hence if it is used from the browser the HTTP cookie is sent if user has logged in else you need to pass headers object. It accepts the optional JSON object as parameter, you can pass the HTTP Headers there. | Key | Description | Required | | --------------- | ------------------------------------------------------------------------------------ | -------- | | `Authorization` | Authorization header passed to the server. It needs `Bearer some_token` as its value | false | It returns the following keys in response `data` object **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Usage** ```js // from browser with HTTP Cookie const { data, errors } = await authRef.logout() // from NodeJS / if HTTP cookie is not used const { data, errors } = await authRef.logout({ Authorization: `Bearer some_token`, }) ``` ### - `validateJWTToken` Function to validate jwt tokens. It expects the JSON object as parameter with following parameters | Key | Description | Required | | ------------ | -------------------------------------------------------------------------------------------------------- | -------- | | `token_type` | Type of token that needs to be validated. It can be one of `access_token`, `refresh_token` or `id_token` | `true` | | `token` | Jwt token string | `true` | | `roles` | Array of roles to validate jwt token for | `false` | It returns the following keys in response `data` object **Response** | Key | Description | | ---------- | -------------------------------------------------- | | `is_valid` | Boolean indicating if given token was valid or not | | `claims` | Decoded JWT claims of the validated token | **Sample Usage** ```js const { data, errors } = await authRef.validateJWTToken({ token_type: `access_token`, token: `some jwt token string`, }) ``` ### - `validateSession` Function to validate cookie / browser session. It expects the JSON object as parameter with following parameters | Key | Description | Required | | -------- | --------------------------------------------------------------------------------------------------- | -------- | | `cookie` | browser session cookie value. If not present it will need coookie present in header as https cookie | `false` | | `roles` | Array of roles to validate jwt token for | `false` | It returns the following keys in response `data` object **Response** | Key | Description | | ---------- | -------------------------------------------------- | | `is_valid` | Boolean indicating if given token was valid or not | | `user` | User object with all the basic profile information | **Sample Usage** ```js const { data, errors } = await authRef.validateSession({ cookie: ``, }) ``` ### - `checkPermissions` Function to evaluate one or more fine-grained authorization (FGA) permission checks against the embedded [OpenFGA](https://openfga.dev) engine, in a single call. `results` come back in the same order as `checks` and echo each pair. This function makes an authorized request, hence from the browser the HTTP cookie is sent automatically if the user has logged in. From NodeJS pass the `Authorization` header as the optional second argument. The subject defaults to the caller's token. An optional `user` ("type:id", or a bare id treated as `user:`) is honored only for super-admins or when it equals the caller's own token subject; anything else is rejected by the server — never silently ignored. For complete worked scenarios — Express middleware, list filtering, and tuple lifecycle — see [Authorization recipes](/core/authorization#9-real-world-recipes). It accepts 2 JSON objects as its parameters. 1. data - Permission checks to evaluate 2. headers - To pass Authorization header (optional in the browser) Here are the keys that the `data` object accepts | Key | Description | Required | | -------- | ----------------------------------------------------------------------------------------------------------------------------- | -------- | | `checks` | Array of checks, each `{ relation, object, contextual_tuples? }`. `contextual_tuples` (array of `{ user, relation, object }`) are evaluated for that check only and never persisted | true | | `user` | Subject override ("type:id", or a bare id treated as `user:`). Honored only for super-admins or self; defaults to the caller | false | It returns the following keys in response `data` object **Response** | Key | Description | | --------- | --------------------------------------------------------------------------------------------------- | | `results` | One result per supplied check, in order, each `{ relation, object, allowed }` echoing the checked pair | **Sample Usage** ```js const { data, errors } = await authRef.checkPermissions( { checks: [ { relation: 'can_view', object: 'document:1' }, { relation: 'can_edit', object: 'document:1' }, ], }, { Authorization: `Bearer ${token}` }, // omit in the browser to use the cookie ); if (data?.results?.[0]?.allowed) { // caller may view document:1 } // "What-if" check with contextual tuples (evaluated for this call only): const { data: whatIf } = await authRef.checkPermissions( { checks: [ { relation: 'can_view', object: 'document:1', contextual_tuples: [ { user: 'user:1b9d…', relation: 'viewer', object: 'document:1' }, ], }, ], }, { Authorization: `Bearer ${token}` }, ); ``` ### - `listPermissions` Function to list which objects of a given type the subject holds a relation on — ideal for filtering a list page down to what the user may see ("which `object_type`s can I `relation`?"). Subject resolution follows the same rules as `checkPermissions`. It accepts 2 JSON objects as its parameters. 1. data - Relation / object type to enumerate 2. headers - To pass Authorization header (optional in the browser) Here are the keys that the `data` object accepts | Key | Description | Required | | ------------- | ------------------------------------------------------------------------------------------------------ | -------- | | `relation` | Relation to list for (e.g. `can_view`) | true | | `object_type` | Object type to enumerate (e.g. `document`) | true | | `user` | Subject override ("type:id", or a bare id treated as `user:`). Honored only for super-admins or self | false | It returns the following keys in response `data` object **Response** | Key | Description | | ------------- | ------------------------------------------------------------------------------------------ | | `objects` | Distinct fully-qualified ids of the objects the subject holds the relation on, e.g. `["document:1"]` | **Sample Usage** ```js const { data, errors } = await authRef.listPermissions( { relation: 'can_view', object_type: 'document' }, { Authorization: `Bearer ${token}` }, ); // data?.objects => ['document:1', 'document:7', ...] ``` ### - `verifyOtp` Function to verify OTP sent to the user when they login. It accepts JSON object as a parameter with following keys | Key | Description | Required | | -------------- | -------------------------------------------------- | -------- | | `email` | Email address of user | false | | `phone_number` | Phone number of user | false | | `otp` | OTP (One Time Password) sent to user email address | true | | `is_totp` | Set to `true` when verifying/enrolling a TOTP code instead of an email/SMS OTP | false | | `state` | Opaque state string round-tripped through the flow | false | Either `email` or `phone_number` is required It returns the following keys in response `data` object **Response** | Key | Description | | ---------------------- | ------------------------------------------------------------------------------------------------------ | | `message` | Error / Success message from server | | `access_token` | accessToken that frontend application can use for further authorized requests | | `expires_in` | timestamp when the current token is going to expire, so that frontend can request for new access token | | `id_token` | JWT token holding the user information | | `refresh_token` | When scope includes `offline_access`, Long living token is returned which can be used to get new access tokens. This is rotated with each request | | `user` | User object with all the basic profile information | | `should_show_email_otp_screen` | Is set to true if email based multi factor authentication is enabled | | `should_show_mobile_otp_screen` | Is set to true if mobiled based multi factor authentication is enabled | | `should_show_totp_screen` | Is set to true if totp based multi factor authentication is enabled | | `should_offer_webauthn_mfa_verify` | Is set to true if the user should be offered to verify with an existing passkey as their second factor | | `should_offer_webauthn_mfa_setup` | Is set to true if the user should be offered to enroll a passkey as their second factor | | `should_offer_email_otp_mfa_setup` | Is set to true if the user should be offered email-OTP MFA enrollment | | `should_offer_sms_otp_mfa_setup` | Is set to true if the user should be offered SMS-OTP MFA enrollment | | `authenticator_scanner_image` | If totp registration is pending it sends base64 encoded image string that can be rendered by totp app scanners like Google Authentication | | `authenticator_secret` | If totp registration is pending, then this secret can be used for registration instead of image on authenticator apps | | `authenticator_recovery_codes` | If totp registration is pending, then recovery codes are sent using which totp can be accessed again | **Sample Usage** ```js const { data, errors } = await authRef.verifyOtp({ email: 'foo@bar.com', otp: 'AB123C', }) ``` ### - `resendOtp` Function to resend OTP to the user. It accepts JSON object as a parameter with following keys | Key | Description | Required | | -------------- | --------------------- | -------- | | `email` | Email address of user | false | | `phone_number` | Phone number of user | false | | `state` | Opaque state string round-tripped through the flow | false | Either `email` or `phone_number` is required It returns the following keys in response `data` object **Response** | Key | Description | | ---------------------- | ------------------------------------------------------------------------------------------------------ | | `message` | Error / Success message from server | **Sample Usage** ```js const { data, errors } = await authRef.resendOtp({ email: 'foo@bar.com', }) ``` ### - `deactivateAccount` Function to deactivate user account. This function makes an authorized request, hence if it is used from the browser the HTTP cookie is sent if user has logged in else you need to pass headers object. It accepts 1 JSON object as its parameters. 1. headers - To pass Authorization header Here is sample of `headers` object | Key | Description | Required | | --------------- | -------------------------------------------------------------------------------------- | -------- | | `Authorization` | Authorization header passed to the server. It needs `Bearer access_token` as its value | true | It returns the following keys in response `data` object **Response** | Key | Description | | --------- | ----------------------------------- | | `message` | Success / Error message from server | **Sample Usage** ```js const { data, errors } = await authRef.deactivateAccount({ Authorization: `Bearer some_token`, }) ``` ### - `skipMfaSetup` Function to skip a first-time MFA enrollment offer mid login (the `should_offer_*` gate) when the user has a completed-login state to fall back to. Returns the full `AuthResponse`/token shape (same as `login`/`signup`), since skipping completes the gate. It accepts JSON object as a parameter with following keys | Key | Description | Required | | -------------- | ------------------------------------------------------ | -------- | | `email` | Email address of user | false | | `phone_number` | Phone number of user | false | | `state` | Opaque state string round-tripped through the flow | false | **Sample Usage** ```js const { data, errors } = await authRef.skipMfaSetup({ email: 'foo@bar.com', }) ``` ### - `lockMfa` Function to lock multi-factor authentication for a user by email or phone number. It accepts JSON object as a parameter with following keys | Key | Description | Required | | -------------- | ------------------------ | -------- | | `email` | Email address of user | false | | `phone_number` | Phone number of user | false | It returns the following keys in response `data` object **Response** | Key | Description | | --------- | ------------------------------------ | | `message` | Success / Error message from server | **Sample Usage** ```js const { data, errors } = await authRef.lockMfa({ email: 'foo@bar.com', }) ``` ### - `emailOtpMfaSetup` Function to enroll email-OTP as a multi-factor authentication method — sends an OTP to the user's email to be verified with [`verifyOtp`](#--verifyotp). It accepts an optional JSON object as a parameter with following keys | Key | Description | Required | | -------------- | ------------------------ | -------- | | `email` | Email address of user | false | | `phone_number` | Phone number of user | false | It returns the following keys in response `data` object **Response** | Key | Description | | --------- | ------------------------------------ | | `message` | Success / Error message from server | **Sample Usage** ```js const { data, errors } = await authRef.emailOtpMfaSetup() ``` ### - `smsOtpMfaSetup` Function to enroll SMS-OTP as a multi-factor authentication method — sends an OTP to the user's phone number to be verified with [`verifyOtp`](#--verifyotp). It accepts an optional JSON object as a parameter with following keys | Key | Description | Required | | -------------- | ------------------------ | -------- | | `email` | Email address of user | false | | `phone_number` | Phone number of user | false | It returns the following keys in response `data` object **Response** | Key | Description | | --------- | ------------------------------------ | | `message` | Success / Error message from server | **Sample Usage** ```js const { data, errors } = await authRef.smsOtpMfaSetup() ``` ### - `totpMfaSetup` Function to generate a fresh TOTP secret/QR code/recovery-codes for the caller to enroll as an MFA method — the TOTP twin of `emailOtpMfaSetup`/`smsOtpMfaSetup`. Unlike those, nothing is sent anywhere: the enrollment payload comes back directly in the response, so the caller scans/enters it, then completes enrollment via `verifyOtp({ is_totp: true, otp: '...' })`. It accepts an optional JSON object as a parameter with following keys | Key | Description | Required | | -------------- | ------------------------ | -------- | | `email` | Email address of user | false | | `phone_number` | Phone number of user | false | It returns the following keys in response `data` object **Response** | Key | Description | | ---------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------- | | `message` | Success / Error message from server | | `should_show_totp_screen` | Boolean indicating the TOTP enrollment screen should be shown | | `authenticator_scanner_image` | Base64 encoded QR image that can be scanned by authenticator apps like Google Authenticator | | `authenticator_secret` | Secret that can be entered manually instead of scanning the QR image | | `authenticator_recovery_codes` | Recovery codes that can be used to regain TOTP access if the device is lost | **Sample Usage** ```js const { data, errors } = await authRef.totpMfaSetup() // render data.authenticator_scanner_image, then: await authRef.verifyOtp({ is_totp: true, otp: '123456' }) ``` ### WebAuthn / Passkeys The following methods drive [WebAuthn](https://www.w3.org/TR/webauthn-3/) passkey registration and login. The low-level `webauthn*` methods talk to the server only (GraphQL or REST; the REST routes landed in server 2.4.0) and expect/return the opaque JSON strings the WebAuthn spec defines; the higher-level `registerPasskey`/`loginWithPasskey*` helpers additionally drive the browser's `navigator.credentials` ceremony for you and are what most apps should use directly. ### - `webauthnRegistrationOptions` Function to fetch passkey registration ceremony options from the server. | Argument | Description | Required | | --------------- | ----------------------------------------------------------------------------- | -------- | | `email` | Email of the user to register a passkey for (MFA-session-cookie path only) | false | | `phoneNumber` | Phone number of the user (MFA-session-cookie path only) | false | **Response** | Key | Description | | --------- | ------------------------------------------------------------------ | | `options` | Opaque JSON string (`PublicKeyCredentialCreationOptionsJSON`) to pass to the browser's WebAuthn API | **Sample Usage** ```js const { data, errors } = await authRef.webauthnRegistrationOptions() ``` ### - `webauthnRegistrationVerify` Function to verify a completed passkey registration ceremony. | Key | Description | Required | | ---------------- | --------------------------------------------------------------------------------------------------------- | -------- | | `credential` | Opaque JSON string (`RegistrationResponseJSON`) returned by the browser's WebAuthn ceremony | true | | `name` | Friendly name to store for this credential | false | | `email` | Only used on the MFA-session-cookie path (registering a passkey mid login-time MFA offer) | false | | `phone_number` | Only used on the MFA-session-cookie path | false | | `state` | Opaque state string round-tripped through the flow | false | Returns the full `AuthResponse`/token shape: on the MFA-session-cookie path this also completes the gate, so `access_token` and friends are populated exactly like `verifyOtp`/`skipMfaSetup`. On the ordinary authenticated-settings-page path `access_token` is always `null` — the caller already has one. **Sample Usage** ```js const { data, errors } = await authRef.webauthnRegistrationVerify({ credential: credentialJSON, name: 'My laptop', }) ``` ### - `webauthnLoginOptions` Function to fetch passkey login (assertion) ceremony options from the server. | Argument | Description | Required | | ---------- | ------------------------------------------------------------------------------------------ | -------- | | `email` | Scopes the ceremony to one account's own passkeys. Omit for usernameless (discoverable-credential) login | false | **Response** | Key | Description | | --------- | ------------------------------------------------------------------ | | `options` | Opaque JSON string (`PublicKeyCredentialRequestOptionsJSON`) to pass to the browser's WebAuthn API | **Sample Usage** ```js const { data, errors } = await authRef.webauthnLoginOptions() ``` ### - `webauthnLoginVerify` Function to verify a completed passkey login (assertion) ceremony. | Key | Description | Required | | -------------- | --------------------------------------------------------------------------------------------- | -------- | | `credential` | Opaque JSON string (`AuthenticationResponseJSON`) returned by the browser's WebAuthn ceremony | true | | `state` | Opaque state string round-tripped through the flow | false | Returns the full `AuthResponse`/token shape, same as `login`. **Sample Usage** ```js const { data, errors } = await authRef.webauthnLoginVerify({ credential: credentialJSON, }) ``` ### - `webauthnCredentials` Function to list the caller's enrolled passkeys. Takes no parameters. **Response** (array of) | Key | Description | | ---------------- | ------------------------------------------------------ | | `id` | Credential id | | `name` | Friendly name for the credential | | `transports` | Transports the authenticator advertised (e.g. `internal`, `usb`) | | `created_at` | Timestamp the credential was registered | | `updated_at` | Timestamp the credential was last updated | | `last_used_at` | Timestamp the credential was last used to log in | **Sample Usage** ```js const { data, errors } = await authRef.webauthnCredentials() ``` ### - `webauthnDeleteCredential` Function to delete one of the caller's enrolled passkeys by id. | Argument | Description | Required | | ---------- | ----------------------------- | -------- | | `id` | Id of the credential to delete | true | **Response** | Key | Description | | --------- | ------------------------------------ | | `message` | Success / Error message from server | **Sample Usage** ```js const { data, errors } = await authRef.webauthnDeleteCredential('credential-id') ``` ### - `registerPasskey` High-level helper that drives a full passkey registration ceremony end to end: fetch options from the server (`webauthnRegistrationOptions`), prompt the platform authenticator via the browser's WebAuthn API, then verify (`webauthnRegistrationVerify`). Normally requires an authenticated session (a passkey is added to the caller's own account) — pass `mfaSetup` to instead authenticate via the MFA session cookie mid a login-time MFA offer. | Argument | Description | Required | | ------------ | ----------------------------------------------------------------------------------------------------- | -------- | | `name` | Friendly name to store for this credential | false | | `mfaSetup` | `{ email?, phoneNumber?, state? }` — only used to authenticate via the MFA-session-cookie path | false | **Sample Usage** ```js const { data, errors } = await authRef.registerPasskey('My laptop') ``` ### - `loginWithPasskey` High-level helper that drives a full passkey login ceremony end to end. Omit `email` for a usernameless (discoverable-credential) login; pass it to scope the ceremony to one account's own passkeys (the MFA-alternative flow). | Argument | Description | Required | | ---------- | ------------------------------------------------------------------------------------------------------------------- | -------- | | `email` | Scopes the ceremony to one account's own passkeys | false | | `opts` | `{ mediation?: CredentialMediationRequirement, signal?: AbortSignal }` — pass `mediation: 'conditional'` for passkey autofill (prefer `loginWithPasskeyAutofill` instead) | false | **Sample Usage** ```js const { data, errors } = await authRef.loginWithPasskey() ``` ### - `loginWithPasskeyAutofill` Starts a "passkey autofill" (conditional mediation) login: the browser offers discoverable passkeys inline in a username field's autofill dropdown rather than a modal. The returned promise resolves only when the user actually picks a passkey (or rejects when aborted/cancelled) — fire it on mount and ignore abort errors. Requires an `` on the page. Takes no parameters; only one autofill ceremony runs at a time (a new call, or an explicit modal `loginWithPasskey()`, aborts the previous one). **Sample Usage** ```js useEffect(() => { authRef.loginWithPasskeyAutofill().then(({ data }) => { if (data?.access_token) { // logged in via autofilled passkey } }) return () => authRef.cancelPasskeyAutofill() }, []) ``` ### - `cancelPasskeyAutofill` Aborts a pending `loginWithPasskeyAutofill` ceremony, e.g. on component unmount. Safe to call when none is in flight. Synchronous, returns nothing. **Sample Usage** ```js authRef.cancelPasskeyAutofill() ``` ### - `isWebauthnSupported` Standalone function (not a method on the `Authorizer` instance) that reports whether the current browser supports the WebAuthn `PublicKeyCredential` JSON APIs this SDK's passkey methods rely on. **Sample Usage** ```js import { isWebauthnSupported } from '@authorizerdev/authorizer-js' if (isWebauthnSupported()) { // show a "Sign in with a passkey" button } ``` ### - `parseMfaRedirectParams` Standalone function (not a method on the `Authorizer` instance) that parses the `mfa_required` / `mfa_methods` / `mfa_gate` query params the server's OAuth callback appends to the redirect URL instead of the normal `state`/`code` params when a first-time MFA offer or verification is needed before a token can be issued. Useful on the page your OAuth `redirectURL` points to. | Argument | Description | Required | | ---------- | ------------------------------------------------------------------------------------------------------------- | -------- | | `url` | The full redirect URL (e.g. `window.location.href`), or a `URL` instance. Must be absolute — a bare path/search string throws | true | Returns `null` if the URL has no `mfa_required=1` param, otherwise an object: | Key | Description | | -------------- | --------------------------------------------------------------------------------------------------- | | `mfaRequired` | Always `true` when non-null | | `mfaMethods` | Raw method-name strings from the server (e.g. `totp`, `webauthn`, `email_otp`, `sms_otp`) | | `mfaGate` | `'verify'` — the user has a completed second factor to challenge; or `'offer'` — first-time enrollment with a Skip option. Defaults to `'offer'` when absent | **Sample Usage** ```js import { parseMfaRedirectParams } from '@authorizerdev/authorizer-js' const params = parseMfaRedirectParams(window.location.href) if (params?.mfaRequired) { // route to the MFA setup/verify screen for params.mfaMethods } ``` --- ## Getting Started (4) [`@authorizerdev/authorizer-js`](https://www.npmjs.com/package/@authorizerdev/authorizer-js) is universal javaScript SDK for Authorizer API. It supports: - [UMD (Universal Module Definition)](https://github.com/umdjs/umd) build for browsers - [CommonJS(cjs)](https://flaviocopes.com/commonjs/) build for NodeJS version that don't support ES Modules - [ESM (ES Modules)](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/) build for modern javascript standard, i.e. ES Modules Here is a quick guide on getting started with [`@authorizerdev/authorizer-js`](/sdks/authorizer-js) package. ### Step 1: Get Authorizer Instance Deploy production ready Authorizer instance using one click deployment options available below | **Infra provider** | **One-click link** | **Additional information** | | :----------------: | :-----------------: | :----------------------------------------------------: | | Railway.app | [Deploy on Railway](https://railway.com/deploy/authorizer-1?referralCode=FEF4uT&utm_medium=integration&utm_source=template&utm_campaign=generic) | [docs](/deployment/railway) | | Heroku | [Deploy to Heroku](https://heroku.com/deploy?template=https://github.com/authorizerdev/authorizer-heroku) | [docs](/deployment/heroku) | | Render | [Deploy to Render](https://render.com/deploy?repo=https://github.com/authorizerdev/authorizer-render) | [docs](/deployment/render) | For more information check [docs](/getting-started/) ### Step 2: Setup Instance Start your Authorizer instance with the required CLI flags: ```bash ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` Note the `--client-id` value -- you will need it in the SDK configuration below. Check [Server Configuration](/core/server-config) for all available flags. ### Step 3 - Install SDK Load the `@authorizerdev/authorizer-js` library and initialize the authorizer object. Authorizer object can be instantiated with JSON object with following keys in its constructor. | Key | Description | | --------------- | ------------------------------------------------------------------------------------------------ | | `authorizerURL` | Authorizer server endpoint | | `redirectURL` | URL to which you would like to redirect the user in case of successful login | | `clientID` | Your client identifier (the value of `--client-id` flag used when starting the server) | | `extraHeaders` | Optional JSON object that you can pass to send extra headers to your gateway / authorizer server | **Example** ```js const authRef = new Authorizer({ authorizerURL: 'YOUR_AUTHORIZER_INSTANCE_URL', redirectURL: window.location.origin, clientID: 'YOUR_CLIENT_ID', // value of --client-id flag used to start the server }) ``` #### UMD - Step 1: Load Javascript using CDN ```html ``` - Step 2: Use the library to instantiate `Authorizer` instance and access [various methods](/sdks/authorizer-js/functions) ```html ``` #### CommonJS - Step 1: Install dependencies ```sh npm i --save @authorizerdev/authorizer-js OR yarn add @authorizerdev/authorizer-js ``` - Step 2: Import and initialize the authorizer instance ```js const { Authorizer } = require("@authorizerdev/authorizer-js"); const authRef = new Authorizer({ authorizerURL: "https://app.heroku.com", redirectURL: "http://app.heroku.com/app", clientID: "YOUR_CLIENT_ID", }); async function main() { await authRef.login({ email: "foo@bar.com", password: "test", }); } ``` #### ES Modules - Step 1: Install dependencies ```sh npm i --save @authorizerdev/authorizer-js OR yarn add @authorizerdev/authorizer-js ``` - Step 2: Import and initialize the authorizer instance ```js import { Authorizer } from '@authorizerdev/authorizer-js' const authRef = new Authorizer({ authorizerURL: 'AUTHORIZER_URL', redirectURL: 'YOUR_APP', clientID: 'YOUR_CLIENT_ID', // value of --client-id flag used to start the server }) async function main() { await authRef.login({ email: 'foo@bar.com', password: 'test', }) } ``` ### Step 4: Fine-grained authorization (FGA) Authorizer ships with an embedded [OpenFGA](https://openfga.dev) relationship-based authorization (ReBAC) engine. The SDK exposes two client-facing methods to query it — [`checkPermissions`](/sdks/authorizer-js/functions#--checkpermissions) and [`listPermissions`](/sdks/authorizer-js/functions#--listpermissions). In the browser the session cookie is used automatically; from NodeJS pass the `Authorization` header. ```js // Batch permission checks in one round trip — results come back in order: const { data } = await authRef.checkPermissions( { checks: [ { relation: 'can_view', object: 'document:1' }, { relation: 'can_edit', object: 'document:1' }, ], }, { Authorization: `Bearer ${token}` }, // omit in the browser ) if (data?.results?.[0]?.allowed) { // caller may view document:1 } // List everything the caller may see: const { data: list } = await authRef.listPermissions( { relation: 'can_view', object_type: 'document' }, { Authorization: `Bearer ${token}` }, ) // list?.objects => ['document:1', 'document:7', ...] ``` See [Authorization (FGA)](/core/authorization) for the model, tuples, and real-world recipes. --- ## Protocols & Admin API (Authorizer-python) _Added in `authorizer-py` for Authorizer **2.3.0-rc.9**._ ### Protocol selection Both the sync (`AuthorizerClient`) and async (`AsyncAuthorizerClient`) user clients can talk to the server over three wire protocols. **`graphql` is the default** and is 100% backward compatible — existing code keeps working unchanged. | `protocol=` | Transport | Notes | | ----------- | ------------------------------- | ---------------------------------------------- | | `"graphql"` | `POST /graphql` | Default. | | `"rest"` | Typed `POST/GET /v1/...` routes | Same flat responses as GraphQL. | | `"grpc"` | Generated gRPC stub | Uses a **separate endpoint** (default `:9091`). | As of 2.3.0-rc.9 all public methods work over every protocol, and all three return **identical flat response shapes**. ```python from authorizer import AuthorizerClient, LoginRequest # REST client = AuthorizerClient( client_id="YOUR_CLIENT_ID", authorizer_url="https://your-instance.authorizer.dev", protocol="rest", ) token = client.login(LoginRequest(email="user@example.com", password="Abc@123")) ``` #### gRPC gRPC requires the optional extra: ```bash pip install 'authorizer-py[grpc]' ``` It listens on its own port, separate from the HTTP URL. When `grpc_endpoint` is omitted, the target is derived from `authorizer_url`'s host with the default gRPC port `9091`. ```python client = AuthorizerClient( client_id="YOUR_CLIENT_ID", authorizer_url="https://your-instance.authorizer.dev", protocol="grpc", grpc_endpoint="your-instance.authorizer.dev:9091", # optional ) ``` > OAuth endpoints (`/oauth/token`, `/oauth/revoke`) always use REST regardless of the > selected protocol. ### Admin client The admin API is a **separate client** constructed with the admin secret (the value of `--admin-secret`) — `AuthorizerAdminClient` (sync) and `AsyncAuthorizerAdminClient` (async). Admin auth is sent on every call as the `x-authorizer-admin-secret` header (gRPC: metadata key `x-authorizer-admin-secret`). ```python from authorizer import AuthorizerAdminClient admin = AuthorizerAdminClient( authorizer_url="https://your-instance.authorizer.dev", admin_secret="YOUR_ADMIN_SECRET", ) # List users res = admin.users() for u in res.users: print(u.email) admin.close() ``` The async client mirrors the sync one method-for-method; `await` the calls and use `async with` / `await admin.aclose()`. #### Constructor options ```python AuthorizerAdminClient( authorizer_url: str, admin_secret: str, extra_headers: dict[str, str] | None = None, protocol: str = "graphql", grpc_endpoint: str = "", ) ``` | Parameter | Description | Required | | ---------------- | ------------------------------------------------------------------ | -------- | | `authorizer_url` | Base URL of your Authorizer instance, **no trailing slash**. | yes | | `admin_secret` | Value of `--admin-secret`. | yes | | `extra_headers` | Extra headers sent on every admin request. | no | | `protocol` | `"graphql"` (default), `"rest"`, or `"grpc"`. | no | | `grpc_endpoint` | gRPC target (default: URL host + `:9091`). | no | #### Admin methods Each method declares which protocols support it. Calling a method on an unsupported protocol raises a clear error early rather than emitting a 404. > **⚠ Destructive:** `delete_user`, `delete_webhook`, `delete_email_template`, > `fga_write_model` (overwrites the model), `fga_delete_tuples`, `fga_reset` (wipes all > FGA data), `delete_client`, `rotate_client_secret`/`rotate_scim_token` (invalidate the > old secret/token), `delete_trusted_issuer`, `delete_organization`, > `delete_org_oidc_connection`/`delete_org_saml_connection`, `delete_saml_service_provider`, > `retire_saml_idp_key`, `delete_org_domain`, and `delete_scim_endpoint` permanently change > or remove data — see each method's note below. ##### Auth, session & meta | Method | Description | grpc | rest | gql | | --------------- | ---------------------------------------- | :--: | :--: | :-: | | `admin_login` | Exchange the admin secret for a session. | ✓ | ✓ | ✓ | | `admin_logout` | End the admin session. | ✓ | ✓ | ✓ | | `admin_session` | Get the current admin session. | ✓ | ✓ | ✓ | | `admin_meta` | Server metadata / feature flags. | ✓ | ✓ | ✓ | ##### Users & access | Method | Description | grpc | rest | gql | | ------------------------ | ----------------------------------- | :--: | :--: | :-: | | `users` | List users (paginated). | ✓ | ✓ | ✓ | | `user` | Get a single user. | ✓ | ✓ | ✓ | | `update_user` | Update a user. | ✓ | ✓ | ✓ | | `delete_user` | **Delete a user.** | ✓ | ✓ | ✓ | | `verification_requests` | List pending verification requests. | ✓ | ✓ | ✓ | | `revoke_access` | Revoke a user's access. | ✓ | ✓ | ✓ | | `enable_access` | Re-enable a user's access. | ✓ | ✓ | ✓ | | `invite_members` | Invite members by email. | ✓ | ✓ | ✓ | ##### Webhooks | Method | Description | grpc | rest | gql | | ---------------- | -------------------------------- | :--: | :--: | :-: | | `add_webhook` | Create a webhook. | ✓ | ✓ | ✓ | | `update_webhook` | Update a webhook. | ✓ | ✓ | ✓ | | `delete_webhook` | **Delete a webhook.** | ✓ | ✓ | ✓ | | `get_webhook` | Get a single webhook. | ✓ | ✓ | ✓ | | `webhooks` | List webhooks. | ✓ | ✓ | ✓ | | `webhook_logs` | List webhook delivery logs. | ✓ | ✓ | ✓ | | `test_endpoint` | Send a test event to a webhook. | ✓ | ✓ | ✓ | ##### Email templates | Method | Description | grpc | rest | gql | | ----------------------- | ---------------------------- | :--: | :--: | :-: | | `add_email_template` | Create an email template. | ✓ | ✓ | ✓ | | `update_email_template` | Update an email template. | ✓ | ✓ | ✓ | | `delete_email_template` | **Delete an email template.**| ✓ | ✓ | ✓ | | `email_templates` | List email templates. | ✓ | ✓ | ✓ | ##### Audit | Method | Description | grpc | rest | gql | | ------------ | ----------------- | :--: | :--: | :-: | | `audit_logs` | List audit logs. | ✓ | ✓ | ✓ | ##### FGA admin | Method | Description | grpc | rest | gql | | ------------------- | ---------------------------------------- | :--: | :--: | :-: | | `fga_get_model` | Get the current FGA model. | ✓ | ✓ | ✓ | | `fga_write_model` | **Write/overwrite the FGA model.** | ✓ | ✓ | ✓ | | `fga_write_tuples` | Write relationship tuples. | ✓ | ✓ | ✓ | | `fga_delete_tuples` | **Delete relationship tuples.** | ✓ | ✓ | ✓ | | `fga_read_tuples` | Read relationship tuples. | ✓ | ✓ | ✓ | | `fga_list_users` | List users with a relation to an object. | ✓ | ✓ | ✓ | | `fga_expand` | Expand a relation into its userset. | ✓ | ✓ | ✓ | | `fga_reset` | **Reset all FGA data.** | ✓ | ✓ | ✓ | ##### Clients (service accounts / machine identities) Clients created here authenticate over `/oauth/token` with the `client_credentials` and token-exchange grants — see [Machine-to-machine & agent delegation](./functions#oauth-rest). Since 0.5.0 clients carry `backchannel_token_delivery_mode` (`"poll"` when the client may use [CIBA](../../enterprise/ciba)), and `create_client`/`update_client` accept it. Reading it needs **server 2.5.0+**: against an older server, the client methods fail over GraphQL with *Cannot query field*. Upgrade the server, or stay on 0.4.x. | Method | Description | grpc | rest | gql | | ---------------------- | ------------------------------------------------ | :--: | :--: | :-: | | `create_client` | Create a client. `client_secret` is shown **once**. | ✓ | ✓ | ✓ | | `update_client` | Update a client. | ✓ | ✓ | ✓ | | `delete_client` | **Delete a client** — its tokens stop resolving. | ✓ | ✓ | ✓ | | `rotate_client_secret` | **Rotate a client's secret** (old one invalidated, new one shown once). | ✓ | ✓ | ✓ | | `get_client` | Get a single client. | ✓ | ✓ | ✓ | | `clients` | List clients (paginated). | ✓ | ✓ | ✓ | ##### Trusted issuers External OIDC/JWT issuers Authorizer accepts tokens from (e.g. for federated machine/agent identities). | Method | Description | grpc | rest | gql | | ------------------------ | ----------------------------------------- | :--: | :--: | :-: | | `add_trusted_issuer` | Add a trusted issuer. | ✓ | ✓ | ✓ | | `update_trusted_issuer` | Update a trusted issuer. | ✓ | ✓ | ✓ | | `delete_trusted_issuer` | **Delete a trusted issuer** — its tokens stop authenticating. | ✓ | ✓ | ✓ | | `get_trusted_issuer` | Get a single trusted issuer. | ✓ | ✓ | ✓ | | `trusted_issuers` | List trusted issuers (paginated). | ✓ | ✓ | ✓ | ##### SAML Identity Provider Authorizer acting as a SAML IdP for downstream service providers. | Method | Description | grpc | rest | gql | | -------------------------------- | -------------------------------------------------------------------- | :--: | :--: | :-: | | `create_saml_service_provider` | Register a downstream SP. | ✓ | ✓ | ✓ | | `update_saml_service_provider` | Update a registered SP. | ✓ | ✓ | ✓ | | `delete_saml_service_provider` | **Delete a registered SP** — it can no longer be issued assertions. | ✓ | ✓ | ✓ | | `get_saml_service_provider` | Get a single registered SP. | ✓ | ✓ | ✓ | | `list_saml_service_providers` | List registered SPs (paginated). | ✓ | ✓ | ✓ | | `rotate_saml_idp_cert` | Generate a new signing keypair; the previous key stays active. | ✓ | ✓ | ✓ | | `retire_saml_idp_key` | **Retire a signing key** — drops out of IdP metadata; cannot retire the current key. | ✓ | ✓ | ✓ | | `list_saml_idp_keys` | List signing keys (`-> list[SAMLIDPKey]`). | ✓ | ✓ | ✓ | | `import_saml_sp_metadata` | Parse pasted SP metadata XML (no record is created, no URL fetched). | ✓ | ✓ | ✓ | ##### Organizations, org SSO, SCIM and org domains Multi-tenant organizations, their membership, upstream SSO connections, inbound SCIM provisioning, and the verified domains that drive home-realm discovery. These were GraphQL-only until server 2.4.0, which added the proto RPCs and REST bindings — against an older server they still work over `graphql` only. Most are authorized for a super-admin **or** that organization's own org-admin (the reserved `authorizer:org_admin` role); the platform-wide operations (`organizations`, `create_organization`, `delete_organization`, `add_verified_org_domain`) stay super-admin only. | Method | Description | gql | rest | grpc | | ------ | ----------- | :-: | :--: | :--: | | `create_organization` | Create an organization. | ✓ | ✓ | ✓ | | `update_organization` | Update an organization. | ✓ | ✓ | ✓ | | `delete_organization` | **Delete an organization.** | ✓ | ✓ | ✓ | | `get_organization` | Get a single organization. | ✓ | ✓ | ✓ | | `organizations` | List organizations (paginated). | ✓ | ✓ | ✓ | | `add_org_member` | Add a member to an organization. | ✓ | ✓ | ✓ | | `remove_org_member` | Remove a member from an organization. | ✓ | ✓ | ✓ | | `org_members` | List an organization's members. | ✓ | ✓ | ✓ | | `user_organizations` | List the organizations a user belongs to. | ✓ | ✓ | ✓ | | `request_org_domain` | Start home-realm-discovery domain verification (DNS challenge). | ✓ | ✓ | ✓ | | `verify_org_domain` | Verify a requested domain's DNS challenge. | ✓ | ✓ | ✓ | | `add_verified_org_domain` | Super-admin only: trust-assert a domain as verified, skipping the DNS challenge. | ✓ | ✓ | ✓ | | `delete_org_domain` | **Delete a verified org domain** — it stops routing logins to the org. | ✓ | ✓ | ✓ | | `org_domains` | List an organization's verified domains. | ✓ | ✓ | ✓ | | `create_org_oidc_connection` | Create an org-scoped OIDC SSO connection. | ✓ | ✓ | ✓ | | `update_org_oidc_connection` | Update an org-scoped OIDC SSO connection. | ✓ | ✓ | ✓ | | `delete_org_oidc_connection` | **Delete an org-scoped OIDC SSO connection** — members lose this SSO path. | ✓ | ✓ | ✓ | | `get_org_oidc_connection` | Get an org-scoped OIDC SSO connection. | ✓ | ✓ | ✓ | | `create_org_saml_connection` | Create an org-scoped SAML SSO connection. | ✓ | ✓ | ✓ | | `update_org_saml_connection` | Update an org-scoped SAML SSO connection. | ✓ | ✓ | ✓ | | `delete_org_saml_connection` | **Delete an org-scoped SAML SSO connection** — members lose this SSO path. | ✓ | ✓ | ✓ | | `get_org_saml_connection` | Get an org-scoped SAML SSO connection. | ✓ | ✓ | ✓ | | `create_scim_endpoint` | Create a SCIM provisioning endpoint. Bearer token shown **once**. | ✓ | ✓ | ✓ | | `rotate_scim_token` | **Rotate a SCIM endpoint's bearer token** (old one invalidated, new one shown once). | ✓ | ✓ | ✓ | | `delete_scim_endpoint` | **Delete a SCIM endpoint** — provisioning stops working. | ✓ | ✓ | ✓ | | `get_scim_endpoint` | Get a single SCIM endpoint. | ✓ | ✓ | ✓ | ##### Clients (service accounts / machine identities) Clients created here authenticate over `/oauth/token` with the `client_credentials` and token-exchange grants — see [Machine-to-machine & agent delegation](./functions#oauth-rest). Since 0.5.0 clients carry `backchannel_token_delivery_mode` (`"poll"` when the client may use [CIBA](../../enterprise/ciba)), and `create_client`/`update_client` accept it. Reading it needs **server 2.5.0+**: against an older server, the client methods fail over GraphQL with *Cannot query field*. Upgrade the server, or stay on 0.4.x. | Method | Description | grpc | rest | gql | | ---------------------- | ------------------------------------------------ | :--: | :--: | :-: | | `create_client` | Create a client. `client_secret` is shown **once**. | ✓ | ✓ | ✓ | | `update_client` | Update a client. | ✓ | ✓ | ✓ | | `delete_client` | **Delete a client** — its tokens stop resolving. | ✓ | ✓ | ✓ | | `rotate_client_secret` | **Rotate a client's secret** (old one invalidated, new one shown once). | ✓ | ✓ | ✓ | | `get_client` | Get a single client. | ✓ | ✓ | ✓ | | `clients` | List clients (paginated). | ✓ | ✓ | ✓ | ##### Trusted issuers External OIDC/JWT issuers Authorizer accepts tokens from (e.g. for federated machine/agent identities). | Method | Description | grpc | rest | gql | | ------------------------ | ----------------------------------------- | :--: | :--: | :-: | | `add_trusted_issuer` | Add a trusted issuer. | ✓ | ✓ | ✓ | | `update_trusted_issuer` | Update a trusted issuer. | ✓ | ✓ | ✓ | | `delete_trusted_issuer` | **Delete a trusted issuer** — its tokens stop authenticating. | ✓ | ✓ | ✓ | | `get_trusted_issuer` | Get a single trusted issuer. | ✓ | ✓ | ✓ | | `trusted_issuers` | List trusted issuers (paginated). | ✓ | ✓ | ✓ | ##### SAML Identity Provider Authorizer acting as a SAML IdP for downstream service providers. | Method | Description | grpc | rest | gql | | -------------------------------- | -------------------------------------------------------------------- | :--: | :--: | :-: | | `create_saml_service_provider` | Register a downstream SP. | ✓ | ✓ | ✓ | | `update_saml_service_provider` | Update a registered SP. | ✓ | ✓ | ✓ | | `delete_saml_service_provider` | **Delete a registered SP** — it can no longer be issued assertions. | ✓ | ✓ | ✓ | | `get_saml_service_provider` | Get a single registered SP. | ✓ | ✓ | ✓ | | `list_saml_service_providers` | List registered SPs (paginated). | ✓ | ✓ | ✓ | | `rotate_saml_idp_cert` | Generate a new signing keypair; the previous key stays active. | ✓ | ✓ | ✓ | | `retire_saml_idp_key` | **Retire a signing key** — drops out of IdP metadata; cannot retire the current key. | ✓ | ✓ | ✓ | | `list_saml_idp_keys` | List signing keys (`-> list[SAMLIDPKey]`). | ✓ | ✓ | ✓ | | `import_saml_sp_metadata` | Parse pasted SP metadata XML (no record is created, no URL fetched). | ✓ | ✓ | ✓ | ##### GraphQL-only extras These are the only admin operations with no proto RPC, so they work **over GraphQL only**: | Method | Description | | --------------------------------- | ------------------------------------------------------- | | `admin_signup` | Bootstrap the first admin. | | `update_env` | **Deprecated server-side** — v2 configures everything via CLI flags; the resolver always errors. | | `generate_jwt_keys` | Generate a new JWT signing key pair. | --- ## Fine-Grained Authorization ## Fine-Grained Authorization (FGA) Authorizer ships with an embedded [OpenFGA](https://openfga.dev) relationship-based authorization (ReBAC) engine. The Python SDK exposes two client-facing methods to query it: `check_permissions` and `list_permissions`. Both take a request dataclass and an optional `headers` dict — pass the user's access token as `Authorization: Bearer `. > The subject is pinned server-side from the caller's token. The optional `user` field is > honored only for super-admins or when it equals the caller's own subject. See > [Authorization (FGA)](../../core/authorization) for the model and the > [FGA Guide](../../core/fga-guide) for building one. ### `check_permissions` Evaluate one or more permission checks in a single call (1–100). `results` come back in the same order as `checks` and echo each pair. ```python from authorizer import ( AuthorizerClient, CheckPermissionsRequest, PermissionCheckInput, ) client = AuthorizerClient("YOUR_CLIENT_ID", "https://your-instance.authorizer.dev") auth = {"Authorization": "Bearer USER_ACCESS_TOKEN"} res = client.check_permissions( CheckPermissionsRequest( checks=[ PermissionCheckInput(relation="can_view", object="document:1"), PermissionCheckInput(relation="can_edit", object="document:1"), ] ), headers=auth, ) for r in res.results: print(r.relation, r.object, r.allowed) # can_view document:1 True # can_edit document:1 False ``` #### Contextual tuples Each check accepts optional `contextual_tuples` — extra `{ user, relation, object }` tuples evaluated for that one check only and never persisted. Useful for "what-if" checks and request-time facts: ```python from authorizer import ( AuthorizerClient, CheckPermissionsRequest, PermissionCheckInput, FgaTupleInput, ) client = AuthorizerClient("YOUR_CLIENT_ID", "https://your-instance.authorizer.dev") auth = {"Authorization": "Bearer USER_ACCESS_TOKEN"} res = client.check_permissions( CheckPermissionsRequest( checks=[ PermissionCheckInput( relation="can_view", object="document:1", contextual_tuples=[ FgaTupleInput(user="user:alice", relation="member", object="team:eng"), ], ), ] ), headers=auth, ) print(res.results[0].allowed) ``` ### `list_permissions` List what the subject can access. With both `relation` and `object_type` set it answers "which `object_type`s can I `relation`?"; either or both filters may be omitted, so an empty request returns every permission the subject holds. ```python from authorizer import AuthorizerClient, ListPermissionsRequest client = AuthorizerClient("YOUR_CLIENT_ID", "https://your-instance.authorizer.dev") auth = {"Authorization": "Bearer USER_ACCESS_TOKEN"} res = client.list_permissions( ListPermissionsRequest(relation="can_view", object_type="document"), headers=auth, ) print(res.objects) # ['document:1', 'document:42'] for p in res.permissions: print(p.object, p.relation) print("truncated:", res.truncated) ``` `truncated` is `True` when the result was capped at **1000** entries and more permissions exist — narrow the query with `relation` / `object_type` to retrieve the rest. ### Async usage Both methods are available on `AsyncAuthorizerClient` — `await` them: ```python import asyncio from authorizer import ( AsyncAuthorizerClient, CheckPermissionsRequest, PermissionCheckInput, ) async def main() -> None: auth = {"Authorization": "Bearer USER_ACCESS_TOKEN"} async with AsyncAuthorizerClient( "YOUR_CLIENT_ID", "https://your-instance.authorizer.dev" ) as client: res = await client.check_permissions( CheckPermissionsRequest( checks=[PermissionCheckInput(relation="can_view", object="document:1")] ), headers=auth, ) print(res.results[0].allowed) asyncio.run(main()) ``` ### Permission-aware retrieval A common pattern (e.g. for RAG / AI assistants) is to **pre-filter** what a user is allowed to see before retrieving or ranking it — call `list_permissions` to get the set of accessible object ids, then restrict your query to that set so disallowed content is never returned: ```python allowed = client.list_permissions( ListPermissionsRequest(relation="can_view", object_type="document"), headers=auth, ).objects # e.g. pass `allowed` as a filter to your vector store / database query. visible_docs = [d for d in candidate_docs if d.id in set(allowed)] ``` ### See also - [Authorization (FGA)](../../core/authorization) — the relationship model & API surface. - [FGA Guide](../../core/fga-guide) — building a model, writing tuples, DSL reference. - [Functions](./functions) — the full SDK method reference. --- ## Functions (Authorizer-python) Every method below exists on **both** `AuthorizerClient` (sync) and `AsyncAuthorizerClient` (async). On the async client the calls are coroutines — `await` them. Request objects are dataclasses imported from `authorizer`; responses are dataclasses too. ```python from authorizer import ( AuthorizerClient, AsyncAuthorizerClient, LoginRequest, SignUpRequest, MagicLinkLoginRequest, VerifyOTPRequest, VerifyEmailRequest, ResendOTPRequest, ResendVerifyEmailRequest, ForgotPasswordRequest, ResetPasswordRequest, ValidateJWTTokenRequest, ValidateSessionRequest, SessionQueryRequest, UpdateProfileRequest, GetTokenRequest, RevokeTokenRequest, CheckPermissionsRequest, ListPermissionsRequest, PermissionCheckInput, FgaTupleInput, SkipMfaSetupRequest, LockMfaRequest, OtpMfaSetupRequest, WebauthnRegistrationOptionsRequest, WebauthnRegistrationVerifyRequest, WebauthnLoginOptionsRequest, WebauthnLoginVerifyRequest, WebauthnDeleteCredentialRequest, TokenType, ) ``` ### Authentication & user management | Method | Signature | Returns | | --------------------- | --------------------------------------------------------------- | --------------------------- | | `login` | `login(req: LoginRequest)` | `AuthToken` | | `signup` | `signup(req: SignUpRequest)` | `AuthToken` | | `magic_link_login` | `magic_link_login(req: MagicLinkLoginRequest)` | `GenericResponse` | | `verify_otp` | `verify_otp(req: VerifyOTPRequest)` | `AuthToken` | | `verify_email` | `verify_email(req: VerifyEmailRequest)` | `AuthToken` | | `resend_otp` | `resend_otp(req: ResendOTPRequest)` | `GenericResponse` | | `resend_verify_email` | `resend_verify_email(req: ResendVerifyEmailRequest)` | `GenericResponse` | | `forgot_password` | `forgot_password(req: ForgotPasswordRequest)` | `ForgotPasswordResponse` | | `reset_password` | `reset_password(req: ResetPasswordRequest)` | `GenericResponse` | | `validate_jwt_token` | `validate_jwt_token(req: ValidateJWTTokenRequest)` | `ValidateJWTTokenResponse` | | `validate_session` | `validate_session(req: ValidateSessionRequest)` | `ValidateSessionResponse` | | `get_meta_data` | `get_meta_data()` | `MetaData` | #### Authenticated (pass a bearer token via `headers`) | Method | Signature | Returns | | --------------------- | ------------------------------------------------------------------------------- | ----------------- | | `get_session` | `get_session(req=None, headers=None)` | `AuthToken` | | `get_profile` | `get_profile(headers=None)` | `User` | | `update_profile` | `update_profile(req: UpdateProfileRequest, headers=None)` | `GenericResponse` | | `logout` | `logout(headers=None)` | `GenericResponse` | | `deactivate_account` | `deactivate_account(headers=None)` | `GenericResponse` | #### Fine-grained authorization | Method | Signature | Returns | | -------------------- | --------------------------------------------------------------------------- | --------------------------- | | `check_permissions` | `check_permissions(req: CheckPermissionsRequest, headers=None)` | `CheckPermissionsResponse` | | `list_permissions` | `list_permissions(req: ListPermissionsRequest, headers=None)` | `ListPermissionsResponse` | See the dedicated [Fine-Grained Authorization](./fga) page for usage. #### MFA setup & recovery All take a bearer token via `headers` (or, if the caller doesn't have one yet, an `email`/`phone_number` pair that resolves the in-progress MFA session cookie instead). | Method | Signature | Returns | | ----------------------- | ------------------------------------------------------------------------ | ------------------- | | `skip_mfa_setup` | `skip_mfa_setup(req: SkipMfaSetupRequest, headers=None)` | `AuthToken` | | `lock_mfa` | `lock_mfa(req: LockMfaRequest, headers=None)` | `GenericResponse` | | `email_otp_mfa_setup` | `email_otp_mfa_setup(req: OtpMfaSetupRequest=None, headers=None)` | `GenericResponse` | | `sms_otp_mfa_setup` | `sms_otp_mfa_setup(req: OtpMfaSetupRequest=None, headers=None)` | `GenericResponse` | | `totp_mfa_setup` | `totp_mfa_setup(req: OtpMfaSetupRequest=None, headers=None)` | `AuthToken` | > `lock_mfa` has no OTP fallback — it locks the account and requires admin recovery > (see [admin `update_user`](./admin)) afterward. #### WebAuthn / passkeys | Method | Signature | Returns | | ---------------------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------- | | `webauthn_registration_options` | `webauthn_registration_options(req: WebauthnRegistrationOptionsRequest=None, headers=None)` | `WebauthnRegistrationOptionsResponse` | | `webauthn_registration_verify` | `webauthn_registration_verify(req: WebauthnRegistrationVerifyRequest, headers=None)` | `AuthToken` | | `webauthn_login_options` | `webauthn_login_options(req: WebauthnLoginOptionsRequest=None, headers=None)` | `WebauthnLoginOptionsResponse` | | `webauthn_login_verify` | `webauthn_login_verify(req: WebauthnLoginVerifyRequest, headers=None)` | `AuthToken` | | `webauthn_delete_credential` | `webauthn_delete_credential(req: WebauthnDeleteCredentialRequest, headers=None)` | `GenericResponse` | | `webauthn_credentials` | `webauthn_credentials(headers=None)` | `list[WebauthnCredentialInfo]` | `webauthn_registration_options`/`webauthn_login_options` return a JSON-encoded `options` string to feed straight to the browser's `navigator.credentials.create()` / `.get()`; `webauthn_registration_verify`/`webauthn_login_verify` take the JSON-encoded credential response back. `webauthn_delete_credential` permanently deletes the registered passkey. `webauthn_credentials` lists the authenticated caller's own registered passkeys. #### OAuth (REST) | Method | Signature | Returns | | -------------- | ------------------------------------------ | ------------------ | | `get_token` | `get_token(req: GetTokenRequest)` | `GetTokenResponse` | | `revoke_token` | `revoke_token(req: RevokeTokenRequest)` | `GenericResponse` | `get_token` posts a form-encoded (`application/x-www-form-urlencoded`) request to `/oauth/token` and supports four grants: `authorization_code` (default, needs `code` + `code_verifier`), `refresh_token`, `client_credentials` ([RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749) §4.4), and [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) token exchange. The `client_credentials` and token-exchange grants are **machine / agent-to-agent flows — server-side only**: never send `client_secret`, `client_assertion`, or a `subject_token`/`actor_token` to untrusted or browser code. ##### Machine-to-machine (client_credentials) Get a token for a service account / machine identity created via the [admin `create_client`](./admin) method: ```python from authorizer import ( AuthorizerClient, GetTokenRequest, GRANT_TYPE_CLIENT_CREDENTIALS, ) machine = AuthorizerClient(client_id="SERVICE_CLIENT_ID", authorizer_url="https://your-instance.authorizer.dev") token = machine.get_token( GetTokenRequest(grant_type=GRANT_TYPE_CLIENT_CREDENTIALS, client_secret="SERVICE_CLIENT_SECRET") ) print(token.access_token, token.scope) ``` ##### Agent delegation (RFC 8693 token exchange) An agent acting on behalf of a signed-in user exchanges the user's token plus its own machine token for a delegated token. The original user stays the JWT `sub`; each hop narrows `scope` and appends to the nested `act` claim (re-widening scope is rejected): ```python from authorizer import ( AuthorizerClient, GetTokenRequest, GRANT_TYPE_CLIENT_CREDENTIALS, GRANT_TYPE_TOKEN_EXCHANGE, TOKEN_TYPE_ACCESS_TOKEN, ) agent = AuthorizerClient(client_id="AGENT_CLIENT_ID", authorizer_url="https://your-instance.authorizer.dev") # 1. the agent authenticates as itself machine_token = agent.get_token( GetTokenRequest(grant_type=GRANT_TYPE_CLIENT_CREDENTIALS, client_secret="AGENT_CLIENT_SECRET") ) # 2. exchange the user's token for one delegated to this agent, scoped down delegated = agent.get_token( GetTokenRequest( grant_type=GRANT_TYPE_TOKEN_EXCHANGE, client_secret="AGENT_CLIENT_SECRET", subject_token=user_access_token, subject_token_type=TOKEN_TYPE_ACCESS_TOKEN, actor_token=machine_token.access_token, actor_token_type=TOKEN_TYPE_ACCESS_TOKEN, scope="crm:read", resource="https://crm.internal.example", ) ) print(delegated.access_token) # sub is still the user; act.sub is the agent ``` #### Escape hatch — raw GraphQL For any operation not covered by a typed helper: ```python data = client.graphql_query( query="query { meta { version } }", variables=None, headers=None, ) ``` `graphql_query(query: str, variables=None, headers=None) -> dict` returns the parsed `data` object. ### Human approval (CIBA) Server-side only, Authorizer 2.5.0+. An agent's service account (registered for [CIBA](../../enterprise/ciba)) asks a user to approve one action. `request_approval` sends the request, `poll_approval` polls once (status `pending`, `slow_down`, `approved`, `denied` or `expired`), and `require_approval` does both, raising `AuthorizerError` with `.code` (`access_denied`, `expired_token`, ...) when it is not approved. The async client has the same methods. ```python from authorizer import ApprovalRequest, AuthorizerClient, check_approved_action with AuthorizerClient(AGENT_CLIENT_ID, "https://auth.example.com") as agent: tokens = agent.require_approval(ApprovalRequest( client_secret=AGENT_CLIENT_SECRET, scope="openid payments:write", login_hint=user_id, # or id_token_hint binding_message="Pay $40 to Acme Corp", resource="https://api.example.com/payments", authorization_details=[{"type": "payment_initiation", "amount": 40, "currency": "USD"}], )) # At the resource server, after verifying the JWT: check = check_approved_action( claims, resource="https://api.example.com/payments", agent=AGENT_CLIENT_ID, matches_authorization_details=lambda d: any(x.get("amount") == amount for x in d), ) ``` The token stays valid for 5 minutes; record `claims["ciba"]["req"]` until `exp` if the action must happen once. ### Examples #### Sign up ```python from authorizer import AuthorizerClient, SignUpRequest client = AuthorizerClient("YOUR_CLIENT_ID", "https://your-instance.authorizer.dev") token = client.signup(SignUpRequest( email="user@example.com", password="Abc@123", confirm_password="Abc@123", given_name="Ada", family_name="Lovelace", )) print(token.message, token.access_token) ``` #### Log in and read the profile ```python from authorizer import AuthorizerClient, LoginRequest client = AuthorizerClient("YOUR_CLIENT_ID", "https://your-instance.authorizer.dev") token = client.login(LoginRequest(email="user@example.com", password="Abc@123")) auth = {"Authorization": f"Bearer {token.access_token}"} user = client.get_profile(headers=auth) print(user.id, user.email, user.roles) ``` #### Validate a JWT ```python from authorizer import AuthorizerClient, ValidateJWTTokenRequest, TokenType client = AuthorizerClient("YOUR_CLIENT_ID", "https://your-instance.authorizer.dev") res = client.validate_jwt_token(ValidateJWTTokenRequest( token=access_token, token_type=TokenType.ACCESS_TOKEN, )) print(res.is_valid, res.claims) ``` #### Magic-link login ```python from authorizer import AuthorizerClient, MagicLinkLoginRequest client = AuthorizerClient("YOUR_CLIENT_ID", "https://your-instance.authorizer.dev") res = client.magic_link_login(MagicLinkLoginRequest(email="user@example.com")) print(res.message) # "Please check your inbox!..." ``` ### Request types All request dataclasses serialize via `to_dict()`. Fields shown `| None` are optional. | Type | Key fields | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `LoginRequest` | `password*`, `email`, `phone_number`, `roles`, `scope`, `state` | | `SignUpRequest` | `password*`, `confirm_password*`, `email`, `given_name`, `family_name`, `phone_number`, `roles`, `scope`, `redirect_uri`, `app_data`, … | | `MagicLinkLoginRequest` | `email*`, `roles`, `scope`, `state`, `redirect_uri` | | `VerifyOTPRequest` | `otp*`, `email`, `phone_number`, `is_totp`, `state` | | `VerifyEmailRequest` | `token*`, `state` | | `ResendOTPRequest` | `email`, `phone_number`, `state` | | `ResendVerifyEmailRequest` | `email*`, `identifier` | | `ForgotPasswordRequest` | `email`, `phone_number`, `state`, `redirect_uri` | | `ResetPasswordRequest` | `password*`, `confirm_password*`, `token`, `otp`, `phone_number` | | `ValidateJWTTokenRequest` | `token*`, `token_type*` (`TokenType`), `roles` | | `ValidateSessionRequest` | `cookie`, `roles` | | `SessionQueryRequest` | `roles`, `scope` | | `UpdateProfileRequest` | `email`, `old_password`, `new_password`, `confirm_new_password`, `given_name`, `family_name`, `roles`, `app_data`, … | | `GetTokenRequest` | `code`, `grant_type`, `refresh_token`, `code_verifier`, `client_secret`, `scope`, `client_assertion`, `client_assertion_type`, `subject_token`, `subject_token_type`, `actor_token`, `actor_token_type`, `resource` | | `RevokeTokenRequest` | `refresh_token*` | | `CheckPermissionsRequest` | `checks*` (`list[PermissionCheckInput]`), `user` | | `ListPermissionsRequest` | `relation`, `object_type`, `user` | | `PermissionCheckInput` | `relation*`, `object*`, `contextual_tuples` (`list[FgaTupleInput]`) | | `FgaTupleInput` | `user*`, `relation*`, `object*` | | `SkipMfaSetupRequest` | `email`, `phone_number`, `state` | | `LockMfaRequest` | `email`, `phone_number` | | `OtpMfaSetupRequest` | `email`, `phone_number` (shared by `email_otp_mfa_setup` / `sms_otp_mfa_setup` / `totp_mfa_setup`) | | `WebauthnRegistrationOptionsRequest` | `email`, `phone_number` | | `WebauthnRegistrationVerifyRequest` | `credential*`, `name`, `email`, `phone_number`, `state` | | `WebauthnLoginOptionsRequest` | `email` | | `WebauthnLoginVerifyRequest` | `credential*`, `state` | | `WebauthnDeleteCredentialRequest` | `id*` | `* = required` ### Response types All response dataclasses are built via `from_dict()`. | Type | Key fields | | -------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `AuthToken` | `message`, `access_token`, `expires_in`, `id_token`, `refresh_token`, `should_show_*_screen`, `authenticator_*`, `user` | | `User` | `id`, `email`, `email_verified`, `given_name`, `family_name`, `phone_number`, `roles`, `created_at`, `app_data`, … | | `GenericResponse` | `message` | | `ForgotPasswordResponse` | `message`, `should_show_mobile_otp_screen` | | `ValidateJWTTokenResponse` | `is_valid`, `claims` | | `ValidateSessionResponse` | `is_valid`, `user` | | `MetaData` | `version`, `client_id`, and `is_*_enabled` feature flags (login providers, MFA, sign-up, etc.) | | `GetTokenResponse` | `access_token`, `expires_in`, `id_token`, `refresh_token`, `token_type`, `scope`, `issued_token_type` | | `CheckPermissionsResponse` | `results` (`list[PermissionCheckResult]`) | | `PermissionCheckResult` | `relation`, `object`, `allowed` | | `ListPermissionsResponse` | `objects`, `permissions` (`list[Permission]`), `truncated` | | `Permission` | `object`, `relation` | | `WebauthnRegistrationOptionsResponse` | `options` (JSON-encoded `PublicKeyCredentialCreationOptions`) | | `WebauthnLoginOptionsResponse` | `options` (JSON-encoded `PublicKeyCredentialRequestOptions`) | | `WebauthnCredentialInfo` | `id`, `name`, `transports`, `created_at`, `updated_at`, `last_used_at` | ### Enums | Enum | Values | | ---------------- | ----------------------------------------------------------------------------------------------------- | | `TokenType` | `ACCESS_TOKEN`, `ID_TOKEN`, `REFRESH_TOKEN` | | `ResponseTypes` | `CODE`, `TOKEN` | | `OAuthProviders` | `APPLE`, `GITHUB`, `GOOGLE`, `FACEBOOK`, `LINKEDIN`, `TWITTER`, `MICROSOFT`, `TWITCH`, `ROBLOX`, `DISCORD` | ### OAuth grant / token-type constants Plain string constants (not enums) for building `GetTokenRequest` — pass their values, or the constants themselves, to `grant_type`, `*_token_type`, and `client_assertion_type`: | Constant | Value | | ---------------------------------- | --------------------------------------------------------------- | | `GRANT_TYPE_AUTHORIZATION_CODE` | `"authorization_code"` | | `GRANT_TYPE_REFRESH_TOKEN` | `"refresh_token"` | | `GRANT_TYPE_CLIENT_CREDENTIALS` | `"client_credentials"` | | `GRANT_TYPE_TOKEN_EXCHANGE` | `"urn:ietf:params:oauth:grant-type:token-exchange"` (RFC 8693) | | `TOKEN_TYPE_ACCESS_TOKEN` | `"urn:ietf:params:oauth:token-type:access_token"` | | `TOKEN_TYPE_JWT` | `"urn:ietf:params:oauth:token-type:jwt"` | | `CLIENT_ASSERTION_TYPE_JWT_BEARER` | `"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"` ([RFC 7523](https://datatracker.ietf.org/doc/html/rfc7523)) | ### Error handling The SDK raises two exception types: | Exception | When | | ---------------------------- | ---------------------------------------------------------------- | | `AuthorizerError` | The API returned an error. Has `message`, `errors`, `status`. | | `AuthorizerConnectionError` | A network/transport failure (subclass of `AuthorizerError`). | ```python from authorizer import AuthorizerClient, LoginRequest, AuthorizerError client = AuthorizerClient("YOUR_CLIENT_ID", "https://your-instance.authorizer.dev") try: client.login(LoginRequest(email="user@example.com", password="wrong")) except AuthorizerError as err: print(err.status, err.message) ``` --- ## Getting Started (5) [`authorizer-py`](https://pypi.org/project/authorizer-py/) is the official Python SDK for the [Authorizer](https://authorizer.dev) API. It ships **both a synchronous and an asynchronous client**, full type hints, and dataclass request/response models — including the [fine-grained authorization (FGA)](../../core/authorization) `check_permissions` and `list_permissions` helpers. - Python **3.9+** - Sync (`AuthorizerClient`) and async (`AsyncAuthorizerClient`) clients - Built on [`httpx`](https://www.python-httpx.org/) - Apache-2.0 licensed ### Step 1: Get an Authorizer instance Deploy a production-ready Authorizer instance using one of the one-click options: | **Infra provider** | **One-click link** | **Additional information** | | :----------------: | :-----------------: | :----------------------------------------------------: | | Railway.app | [Deploy on Railway](https://railway.com/deploy/authorizer-1?referralCode=FEF4uT&utm_medium=integration&utm_source=template&utm_campaign=generic) | [docs](/deployment/railway) | | Heroku | [Deploy to Heroku](https://heroku.com/deploy?template=https://github.com/authorizerdev/authorizer-heroku) | [docs](/deployment/heroku) | | Render | [Deploy to Render](https://render.com/deploy?repo=https://github.com/authorizerdev/authorizer-render) | [docs](/deployment/render) | For more information check the [deployment docs](/deployment/). ### Step 2: Set up the instance Start your Authorizer instance with the required CLI flags: ```bash ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` Note the `--client-id` value — you will need it in the SDK configuration below. See [Server Configuration](../../core/server-config) for all available flags. ### Step 3: Install the package ```bash pip install authorizer-py ``` :::warning Use the 0.3.0 pre-release with server 2.4.0 The latest stable release on PyPI is `0.2.0`, which predates server 2.4.0: it lacks `skip_mfa_setup` and still sends the old `PaginatedRequest` GraphQL type for paginated admin queries (renamed to `PaginationRequest` in 2.4.0). Install with `--pre` to pick up the `0.3.0` pre-release until it goes stable. ::: The import name is `authorizer`: ```python from authorizer import AuthorizerClient ``` ### Step 4: Initialize the client #### Synchronous ```python from authorizer import AuthorizerClient, LoginRequest client = AuthorizerClient( client_id="YOUR_CLIENT_ID", authorizer_url="https://your-instance.authorizer.dev", ) token = client.login(LoginRequest(email="user@example.com", password="Abc@123")) print(token.access_token) client.close() ``` Or as a context manager (auto-closes the HTTP session): ```python with AuthorizerClient( client_id="YOUR_CLIENT_ID", authorizer_url="https://your-instance.authorizer.dev", ) as client: token = client.login(LoginRequest(email="user@example.com", password="Abc@123")) print(token.access_token) ``` #### Asynchronous ```python import asyncio from authorizer import AsyncAuthorizerClient, LoginRequest async def main() -> None: async with AsyncAuthorizerClient( client_id="YOUR_CLIENT_ID", authorizer_url="https://your-instance.authorizer.dev", ) as client: token = await client.login( LoginRequest(email="user@example.com", password="Abc@123") ) print(token.access_token) asyncio.run(main()) ``` The async client mirrors the sync client method-for-method; only `await` and the `async with` / `aclose()` lifecycle differ. ### Constructor options ```python AuthorizerClient( client_id: str, authorizer_url: str, redirect_url: str = "", extra_headers: dict[str, str] | None = None, protocol: str = "graphql", grpc_endpoint: str = "", ) ``` | Parameter | Description | Required | | ---------------- | --------------------------------------------------------------------------------- | -------- | | `client_id` | Your Authorizer app's client ID (value of `--client-id`). | yes | | `authorizer_url` | Base URL of your Authorizer instance, **no trailing slash**. | yes | | `redirect_url` | Default redirect URL used by magic-link and forgot-password flows. | no | | `extra_headers` | Extra headers sent on every request (e.g. a custom `Origin` for CSRF). | no | | `protocol` | Wire protocol: `"graphql"` (default), `"rest"`, or `"grpc"`. | no | | `grpc_endpoint` | gRPC target `host:port`, only used when `protocol="grpc"`. See [Protocols & Admin API](./admin). | no | > **CSRF (v2.3.0+):** the SDK automatically sets an `Origin` header so state-changing > requests aren't rejected with `403`. Override it via `extra_headers` if you need a > specific origin. ### Authenticating subsequent requests Methods that act on a logged-in user (`get_profile`, `update_profile`, `logout`, `check_permissions`, `list_permissions`, …) take a `headers` argument — pass the access token as a bearer credential: ```python auth = {"Authorization": f"Bearer {token.access_token}"} user = client.get_profile(headers=auth) print(user.email) ``` ### Next steps - [Functions](./functions) — the complete method, request, and response reference. - [Fine-Grained Authorization](./fga) — `check_permissions` and `list_permissions`. - [Protocols & Admin API](./admin) — `rest`/`grpc` transports and the `AuthorizerAdminClient`. --- ## Components `@authorizerdev/authorizer-react` exports the few components that you can use in your react application. This will help you build authentication and authorization faster for your application. ### Table of contents - [`AuthorizerProvider`](#authorizerprovider) - [`Authorizer`](#authorizer) - [`AuthorizerSignup`](#authorizersignup) - [`AuthorizerBasicAuthLogin`](#authorizerbasicauthlogin) - [`AuthorizerMagicLinkLogin`](#authorizermagiclinklogin) - [`AuthorizerSocialLogin`](#authorizersociallogin) - [`AuthorizerPasskeyLogin`](#authorizerpasskeylogin) - [`AuthorizerForgotPassword`](#authorizerforgotpassword) - [`AuthorizerResetPassword`](#authorizerresetpassword) - [`AuthorizerVerifyOtp`](#authorizerverifyotp) - [`AuthorizerTOTPScanner`](#authorizertotpscanner) - [`AuthorizerMFASetup`](#authorizermfasetup) - [`AuthorizerPasskeyRegister`](#authorizerpasskeyregister) ### `AuthorizerProvider` `AuthorizerProvider` is the container component that wraps all the Authorizer components. It binds the backend configuration in the app and renders various views accordingly. #### Props - `config`: Object to configure the `authorizer` backend URL and redirect URL. It accepts JSON object with following keys | Key | Type | Description | Required | | --------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -------- | | `authorizerURL` | `string` | Authorizer backend URL | `true` | | `redirectURL` | `string` | Frontend application URL or the page where you want to redirect user post login. Default value is `window.location.origin` | `true` | | `clientID` | `string` | Your client identifier (the value of `--client-id` flag used when starting the server) | `false` | | `protocol` | `'graphql' \| 'rest'` | Wire transport for API calls. Default is `'graphql'`. Use `'rest'` to route calls through the typed REST endpoints instead. | `false` | > **Note:** `'grpc'` is not supported in `authorizer-react` because browsers cannot speak raw gRPC. Use `'graphql'` (default) or `'rest'`. `AuthorizerProvider` also accepts one prop alongside `config` (not nested inside it): - `onStateChangeCallback={async (newState) => {}}`: Async callback fired whenever the context state (`user`, `token`, `loading`, `config`) changes. #### Sample Usage ```jsx import { AuthorizerProvider } from '@authorizerdev/authorizer-react' const App = () => { return ( {}} > {/* rest of your components */} ) } ``` ### `Authorizer` A core component that includes: - social logins (incl. Discord, when enabled on the backend) - passkey ("Sign in with a passkey") login, shown automatically when the browser supports [WebAuthn](https://www.w3.org/TR/webauthn-2/) - signup view - login view - forgot password view - multi-factor authentication setup, verification, and locked-account screens, driven by the backend's response to login/signup/passkey requests Pre configured component that shows various login/signup options based on the backend configurations. Make sure it is used as Child of `AuthorizerProvider`. #### Props - `onLogin={(loginResponse)=>{}}`: event called when login form is submitted successfully. - `onSignup={(signupResponse)=>{}}`: event called when signup form is submitted successfully. - `onMagicLinkLogin={(magicLinkResponse)=>{}}`: event called when magic link login form is submitted successfully. - `onForgotPassword={(forgotPasswordResponse)=>{}}`: called when forgot password form is submitted successfully. - `onPasswordReset={()=>{}}`: called after a password reset completes from the forgot-password OTP flow. - `onCancelMfa={()=>{}}`: optional. When provided, a "Back" link is shown on the MFA setup/verify screens (rendered when the URL carries MFA-redirect params, e.g. after an OAuth or magic-link continuation) so the host can send the user elsewhere, such as back to the login URL with the MFA params cleared. - `roles={string[]}`: optional. Restricts which roles a login/signup grants, e.g. `roles={['user']}`. - `signupFieldsOverrides={FormFieldsOverrides}`: optional. Lets you relabel, reword the placeholder of, hide, or make optional the `given_name`, `family_name`, `email_or_phone_number`, `password`, and `confirmPassword` fields on the signup form. Each field accepts `{ label?, placeholder?, hide?, notRequired? }`. #### Sample Usage ```jsx import { Authorizer } from '@authorizerdev/authorizer-react' const LoginPage = () => { return ( <>

Login / Signup


{}} onMagicLinkLogin={(magicLinkResponse) => {}} onSignup={(signupResponse) => {}} onForgotPassword={(forgotPasswordResponse) => {}} /> ) } ``` ### `AuthorizerSignup` A component to render basic authentication singup form. Make sure it is used as Child of `AuthorizerProvider`. #### Props - `onSignup={(response)=>{}}`: event called when signup form is submitted successfully. - `roles={string[]}`: optional. Restricts which roles the created account is granted. - `fieldOverrides={FormFieldsOverrides}`: optional. Per-field `{ label?, placeholder?, hide?, notRequired? }` overrides for `given_name`, `family_name`, `email_or_phone_number`, `password`, and `confirmPassword`. #### Sample Usage ```jsx import { AuthorizerSignup } from '@authorizerdev/authorizer-react' const SignupPage = () => { return ( <>

Signup


{}} /> ) } ``` ### `AuthorizerBasicAuthLogin` A component to render basic authentication login form. Make sure this is used as Child of `AuthorizerProvider`. #### Props - `onLogin={(response)=>{}}`: event called when login form is submitted successfully. - `roles={string[]}`: optional. Restricts which roles the login grants. #### Sample Usage ```jsx import { AuthorizerBasicAuthLogin } from '@authorizerdev/authorizer-react' const LoginPage = () => { return ( <>

Login


{}} /> ) } ``` ### `AuthorizerMagicLinkLogin` A component to render magic link login form. Make sure this is used as Child of `AuthorizerProvider`. #### Props - `onMagicLinkLogin={(response)=>{}}`: event called when magic link login form is submitted successfully. - `roles={string[]}`: optional. Restricts which roles the login grants. #### Sample Usage ```jsx import { AuthorizerMagicLinkLogin } from '@authorizerdev/authorizer-react' const LoginPage = () => { return ( <>

Login


{}} /> ) } ``` ### `AuthorizerSocialLogin` A component to render list of social media login buttons based on backend configurations (Google, GitHub, Facebook, LinkedIn, Apple, Twitter, Microsoft, Twitch, Roblox, and Discord — each shown only when its corresponding `is_*_login_enabled` flag is on). Clicking a button navigates the browser directly to the provider's OAuth flow (`{authorizerURL}/oauth_login/{provider}`); there are no submit callbacks. Make sure this is used as Child of `AuthorizerProvider`. #### Props It has no required props. Both are normally supplied for you when composed inside `Authorizer`. - `urlProps={Record}`: optional. `state`/`scope`/`redirect_uri` (or `redirectURL`) forwarded onto the OAuth redirect URL. - `roles={string[]}`: optional. Restricts which roles the resulting login grants. #### Sample Usage ```jsx import { AuthorizerSocialLogin } from '@authorizerdev/authorizer-react' const LoginPage = () => { return ( <>

Login / Signup


) } ``` #### Where the user lands after social login The button sends a `redirect_uri` to `/oauth_login`, and the user comes back there after the provider. Which one it sends depends on where the component is rendered: | Rendered on | `redirect_uri` sent | Then | |---|---|---| | Your own site (`https://myapp.example.com/login`) | `urlProps.redirect_uri` (or `redirectURL`), else `redirectURL` from `AuthorizerProvider` | The user returns to that URL. Its origin must be in the server's `--allowed-origins` | | Authorizer's login page (`/app/` or `/app/signup`), opened by `/authorize`. _2.2.1 and later, needs Authorizer 2.4.6+_ | The page's own URL, with the `/authorize` parameters in the query string. `urlProps.redirect_uri` is ignored here, because it's the client's callback | `/app` resumes the request through `/authorize`, which checks the client's registered callback, shows consent if needed, and sends the code | | Authorizer's login page with no `/authorize` request | `redirectURL` from `AuthorizerProvider` (`/app`) | The user is signed in on `/app` | The second row needs no code: the hosted login page gets it by upgrading Authorizer, since the page and the server ship in the same image. It only switches on when the page is served from the same origin as `authorizerURL` and its URL carries both `client_id` and `response_type`, so a login page on your own site never changes behaviour. See [Social login inside an authorization request](../../core/oauth2-oidc#social-login-inside-an-authorization-request) for the full flow. ##### Example: social login on your own site ```jsx import { AuthorizerProvider, AuthorizerSocialLogin, } from '@authorizerdev/authorizer-react' // Server: --allowed-origins=https://myapp.example.com const App = () => ( {/* Returns to https://myapp.example.com/dashboard after GitHub/Google/… */} ) ``` ##### Example: a different landing page per screen ```jsx // Send users who sign in from the pricing page back to checkout. ``` ##### Example: Authorizer's own login page during an authorization request Nothing to configure. When `/authorize` opens the login page as ``` https://auth.example.com/app/?client_id=c1&response_type=code&redirect_uri=https://app.example.org/callback&state=st-123&nonce=n-456&… ``` the GitHub button navigates to ``` https://auth.example.com/oauth_login/github?state=st-123&scope=openid%20profile%20email &redirect_uri=https%3A%2F%2Fauth.example.com%2Fapp%2F%3Fclient_id%3Dc1%26response_type%3Dcode%26… ``` and the code reaches `https://app.example.org/callback` through `/authorize`, even though that origin isn't in `--allowed-origins`. With `response_mode=fragment` (`/app/#client_id=…`), the parameters move into the query string, because a server redirect can't carry a fragment. ### `AuthorizerPasskeyLogin` Renders a "Sign in with a passkey" button that performs a passwordless, usernameless (discoverable-credential) WebAuthn login. Unlike social login, there is no backend config flag for this — it renders purely based on browser support (`isWebauthnSupported()`), and renders nothing when the browser can't do WebAuthn or when the org enforces MFA (`config.is_mfa_enforced`), since passkey-as-sole-factor would let a user skip a required second factor. Make sure this is used as Child of `AuthorizerProvider`. If the account resolved by the passkey ceremony needs a second factor, this component internally takes over and renders the MFA setup, verification, or locked-account screen instead of the button — see [`AuthorizerMFASetup`](#authorizermfasetup) and [`AuthorizerVerifyOtp`](#authorizerverifyotp). #### Props - `onLogin={(data)=>{}}`: event called when the passkey login (or the MFA step that follows it) completes successfully. - `onStepChange={(step)=>{}}`: optional. Fired whenever the component switches between `'button' | 'mfa-setup' | 'mfa-verify' | 'locked'`. Useful when rendering other login options alongside this component, so they can be hidden while an MFA screen is showing. #### Sample Usage ```jsx import { AuthorizerPasskeyLogin } from '@authorizerdev/authorizer-react' const LoginPage = () => { return ( <>

Login


{}} /> ) } ``` ### `AuthorizerForgotPassword` A component to render forgot password form. Make sure this is used as Child of `AuthorizerProvider`. #### Props No props exposed for this components #### Sample Usage ```jsx import { AuthorizerForgotPassword } from '@authorizerdev/authorizer-react' const ForgotPasswordPage = () => { return ( <>

Forgot Password?


{}} /> ) } ``` ### `AuthorizerResetPassword` A component that can be used to reset the password. This component can be used in the page, which is configured with the backend as `RESET_PASSWORD_URL`, check [environment variables](/core/server-config) for more details. This component validates the token in the URL sent via email to the user and helps resetting the password. #### Props - `onReset={(response) => {}}`: optional. Called when reset form is submitted. If omitted, the component redirects the browser to `redirect_uri` (from the URL) or the configured `redirectURL` on success. - `showOTPInput={boolean}`: optional, default `false`. Renders an OTP field above the password fields — used for the mobile/phone forgot-password flow, where `AuthorizerForgotPassword` renders this component itself with `showOTPInput` set. - `phone_number={string}`: optional. The phone number the OTP was sent to; required alongside `showOTPInput` for the phone reset flow. #### Sample Usage ```jsx import { AuthorizerResetPassword } from '@authorizerdev/authorizer-react' const ResetPassword = () => { return ( <>

Reset Password


{}} /> ) } ``` ### `AuthorizerVerifyOtp` A component to render the OTP/MFA verification form. It handles email/SMS OTP and [TOTP](https://datatracker.ietf.org/doc/html/rfc6238) codes, and — when offered alongside a code factor — a "Verify with a passkey" WebAuthn option. On SMS OTP it also attempts WebOTP auto-fill (`navigator.credentials.get({ otp: ... })`) so supporting browsers can fill the code automatically. Make sure it is used as Child of `AuthorizerProvider`. #### Props - `email={string}`: optional. User email address the OTP was sent to. Not required for MFA continuations resolved purely from the session cookie (e.g. an OAuth-redirect or passkey-primary-login continuation, where the frontend never learns the identifier). - `phone_number={string}`: optional. User phone number the OTP was sent to, as an alternative to `email`. - `is_totp={boolean}`: optional, default `false`. Set when the pending factor is an authenticator-app (TOTP) code rather than an emailed/texted OTP — changes the help text and disables WebOTP/resend. - `offerWebauthnVerify={boolean}`: optional, default `false`. Shows the "Verify with a passkey" button above the code form when the account also has webauthn as an available MFA factor. - `hasCodeFactor={boolean}`: optional, default `false`. Whether a code-based factor (TOTP, or a verified email/SMS OTP) actually exists to fall back on. When `false` and `offerWebauthnVerify` is `true`, passkey is the only option and the code form is hidden entirely. - `hasSmsOtp={boolean}`: optional, default `false`. True specifically when the pending code factor is SMS-delivered — gates the WebOTP auto-fill call, which only makes sense for an incoming SMS. - `onBack={()=>{}}`: optional. When provided, a "Back" link lets the user leave this challenge (e.g. return to the login screen) instead of being stuck mid-verification. - `onLogin={(response)=>{}}`: event called when the verify-OTP form (or passkey verification) is submitted successfully. #### Sample Usage ```jsx import { AuthorizerVerifyOtp } from '@authorizerdev/authorizer-react' const VerifyOtp = () => { return ( <>

Verify OTP


{}} /> ) } ``` ### `AuthorizerTOTPScanner` Shown right after a user opts into authenticator-app (TOTP) MFA: renders the QR code to scan, the setup key as a manual-entry fallback (with a copy button), the one-time recovery codes (copy/download/print), and then hands off to [`AuthorizerVerifyOtp`](#authorizerverifyotp) to confirm the first code. Make sure it is used as Child of `AuthorizerProvider`. You normally won't render this directly — [`AuthorizerMFASetup`](#authorizermfasetup) renders it for you once TOTP enrolment data is available. #### Props - `authenticator_scanner_image={string}`: required. Base64-encoded QR code image (rendered as `data:image/jpeg;base64,...`). - `authenticator_secret={string}`: required. The manual-entry setup key shown alongside the QR code. - `authenticator_recovery_codes={string[]}`: required. One-time recovery codes shown once, with copy/download/print actions. - `email={string}`: optional. Forwarded to the OTP-confirmation step. - `phone_number={string}`: optional. Forwarded to the OTP-confirmation step. - `onLogin={(response)=>{}}`: optional. Forwarded to the OTP-confirmation step; called once the first TOTP code is verified. - `setView={(v)=>{}}`: optional. Forwarded to the OTP-confirmation step for view-switching hosts (e.g. `Authorizer`'s internal login/signup view state). #### Sample Usage ```jsx import { AuthorizerTOTPScanner } from '@authorizerdev/authorizer-react' const TotpSetup = ({ enrollment }) => { return ( {}} /> ) } ``` ### `AuthorizerMFASetup` The hub where a signed-in (or mid-login) user opts into the MFA methods the server offers: authenticator app (TOTP), passkey, email one-time code, and SMS one-time code. Only methods you flag as `available` are shown, so users only ever see real options. TOTP and passkey have complete in-component enrolment flows ([`AuthorizerTOTPScanner`](#authorizertotpscanner) and [`AuthorizerPasskeyRegister`](#authorizerpasskeyregister)); email/SMS OTP are sent and confirmed via [`AuthorizerVerifyOtp`](#authorizerverifyotp) directly through the SDK, or delegated to your own UI via `onSetupMethod`. Make sure it is used as Child of `AuthorizerProvider`. `Authorizer` (and `AuthorizerSignup` / `AuthorizerBasicAuthLogin` / `AuthorizerPasskeyLogin`) already render this automatically when the backend offers MFA setup during login/signup — you mainly need this directly to build a custom "Security settings" page where a user can add a second factor later. #### Props - `availableMfaMethods={AvailableMfaMethods}`: required. `{ totp?: boolean; passkey?: boolean; emailOtp?: boolean; smsOtp?: boolean }` — which methods to offer. An omitted/`false` value hides that method entirely. - `totpEnrollment={{ authenticator_scanner_image, authenticator_secret, authenticator_recovery_codes }}`: optional. When present, choosing "Set up" for TOTP renders `AuthorizerTOTPScanner` inline with this data immediately. When absent, the component fetches it for you via the SDK's `totpMfaSetup`, unless `onSetupMethod` is supplied. - `onSetupMethod={(method: MfaMethod)=>{}}`: optional escape hatch. Called instead of the default SDK-driven flow when the user picks a method your host wants to handle itself (`'totp' | 'passkey' | 'email_otp' | 'sms_otp'`). - `heading={string}`: optional, default `"Add a second step to sign in"`. Heading text above the method list. - `loginContext={{ email?, phone_number?, state?, onComplete }}`: optional. Present only for the login-time (withheld-token) MFA offer, as opposed to a settings-page "add a second factor" hub. Adds a "Skip for now" action, and completing a method calls `onComplete` with the token the server issues (instead of just closing/refreshing, as a settings-page usage would). - `onBack={()=>{}}`: optional. Shows a "Back" link on the top-level method list so the host can let the user leave MFA setup entirely. - `passkeyRegistered={boolean}`: optional. Whether the signed-in user already has a passkey registered, so the passkey row can show an "Enabled" badge and "Manage" instead of "Set up". It also exports two supporting types: - `AvailableMfaMethods` — the shape of the `availableMfaMethods` prop. - `MfaMethod` — `'totp' | 'passkey' | 'email_otp' | 'sms_otp'`, the union passed to `onSetupMethod`. #### Sample Usage ```jsx import { AuthorizerMFASetup } from '@authorizerdev/authorizer-react' const SecuritySettings = () => { return ( ) } ``` ### `AuthorizerPasskeyRegister` Lets a signed-in user enrol a new passkey (WebAuthn credential) as an MFA / passwordless method, and optionally lists their already-registered passkeys. Complements [`AuthorizerPasskeyLogin`](#authorizerpasskeylogin), which only handles the login ceremony. Since passkey support is a browser capability rather than a server config flag, this renders an "unsupported" notice — instead of nothing — when the browser can't run the WebAuthn ceremony, since in a settings context the user needs to know why the option is missing. Make sure it is used as Child of `AuthorizerProvider`. #### Props - `onSuccess={(data)=>{}}`: optional. Called after a passkey is successfully registered. During the login-time MFA-offer path (see `mfaSetup` below) this carries the `access_token` issued by completing a withheld MFA offer; a plain settings-page add never sets it. - `name={string}`: optional. A friendly name for the credential (e.g. `"MacBook Touch ID"`). When omitted, an inline text field is shown so the user can name it themselves. - `showCredentials={boolean}`: optional, default `false`. Shows the list of already-registered passkeys above the add button. Requires an authenticated session (calls `webauthnCredentials`), so it's off by default. - `mfaSetup={{ email?, phoneNumber?, state? }}`: optional. Present only during a token-withheld login-time MFA offer — authenticates the registration ceremony via the MFA session cookie instead of a bearer token (there isn't one yet), and completing it issues the previously-withheld token. #### Sample Usage ```jsx import { AuthorizerPasskeyRegister } from '@authorizerdev/authorizer-react' const SecuritySettings = () => { return ( {}} /> ) } ``` --- ## Hooks `@authorizerdev/authorizer-react` exports a hook which can be used in any child component for `AuthorizerProvider`. ### `useAuthorizer` It gives global state stored in the context, which can be used further in the component. It also returns few setter methods which can be used to manipulate the state. Here is the complete list of state variables and functions that are returned by `useAuthorizer` hook. | Variable name | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `config` | Root configuration object passed to `AuthorizerProvider` + backend configuration obtained via [`meta`](/sdks/authorizer-js/functions#--getmetadata) api. Includes feature flags such as `is_discord_login_enabled`, `is_webauthn_enabled`, `is_totp_mfa_enabled`, `is_email_otp_mfa_enabled`, `is_sms_otp_mfa_enabled`, and `is_mfa_enforced`. | | `configLoadError` | `string \| null`. Set when the initial `meta` fetch from `authorizerURL` fails (e.g. the backend is unreachable). Login methods that depend on that config — basic auth, signup, social login, magic link — won't render until it succeeds. | | `user` | If not logged in this is `null`, else it includes all the user related information like `email`, `given_name`, `family_name`, `picture`, and [more](/sdks/authorizer-js/functions#--getprofile) | | `token` | If not logged in it is `null` else it is access token string which can be used to make authorized requests | | `loading` | Loading state for the application to know if its fetching token or user profile data | | `setUser` | Function to set user profile information. Accepts JSON object with all the possible profile values | | `setToken` | Function to set token. Accepts string with correct access token value | | `setLoading` | Function to set loading state. Accepts boolean value | | `setAuthData` | Function to set all the state data, `user`, `token`, `loading`, `config`. Accepts object with `{user, token, config, loading}` as value | | `logout` | Function to logout user | | `authorizerRef` | Reference to [authorizer-js](/sdks/authorizer-js) instance which can be used to call [functions](/sdks/authorizer-js/functions) exposed by [authorizer-js](/sdks/authorizer-js) | #### Sample Usage ```jsx import { useAuthorizer } from '@authorizerdev/authorizer-react' const Component = () => { const { user } = useAuthorizer() if (!user) { return null } return
{user.email}
} ``` --- ## Getting Started (6) Authorizer React SDK allows you to implement authentication in your [React](https://reactjs.org/) application quickly. It also allows you to access the user profile. Here is a quick guide on getting started with `@authorizerdev/authorizer-react` package. ### Step 1: Get Authorizer Instance Deploy production ready Authorizer instance using one click deployment options available below | **Infra provider** | **One-click link** | **Additional information** | | :----------------: | :-----------------: | :----------------------------------------------------: | | Railway.app | [Deploy on Railway](https://railway.com/deploy/authorizer-1?referralCode=FEF4uT&utm_medium=integration&utm_source=template&utm_campaign=generic) | [docs](/deployment/railway) | | Heroku | [Deploy to Heroku](https://heroku.com/deploy?template=https://github.com/authorizerdev/authorizer-heroku) | [docs](/deployment/heroku) | | Render | [Deploy to Render](https://render.com/deploy?repo=https://github.com/authorizerdev/authorizer-render) | [docs](/deployment/render) | For more information check [docs](/getting-started/) ### Step 2: Setup Instance Start your Authorizer instance with the required CLI flags: ```bash ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` Note the `--client-id` value -- you will need it in the SDK configuration below. Check [Server Configuration](/core/server-config) for all available flags. ### Step 3 - Install package Install `@authorizerdev/authorizer-react` library ```sh npm i --save @authorizerdev/authorizer-react OR yarn add @authorizerdev/authorizer-react ``` ### Step 4 - Configure Provider and use Authorizer Components Authorizer comes with [react context](https://reactjs.org/docs/context.html) which serves as `Provider` component for the application ```jsx import { AuthorizerProvider, Authorizer, useAuthorizer, } from '@authorizerdev/authorizer-react' const App = () => { return ( ) } const LoginSignup = () => { return } const Profile = () => { const { user } = useAuthorizer() if (user) { return
{user.email}
} return null } ``` ### Updating styles Components in `@authorizerdev/authorizer-react` are designed using css variables and comes with `default.css` which declares this variables. You can modify these css variable to update styling as per your theme: > Note: Given are the default values for the variables. ```css --authorizer-primary-color: #3b82f6; --authorizer-primary-disabled-color: #60a5fa; --authorizer-gray-color: #d1d5db; --authorizer-slate-color: #e2e8f0; --authorizer-white-color: #ffffff; --authorizer-danger-color: #dc2626; --authorizer-success-color: #10b981; --authorizer-text-color: #374151; --authorizer-fonts-font-stack: -apple-system, system-ui, sans-serif; --authorizer-fonts-large-text: 18px; --authorizer-fonts-medium-text: 14px; --authorizer-fonts-small-text: 12px; --authorizer-fonts-tiny-text: 10px; --authorizer-radius-card: 5px; --authorizer-radius-button: 5px; --authorizer-radius-input: 5px; ``` ### Examples Please check the [example repo](https://github.com/authorizerdev/examples) to see how to use this component library. --- ## Integration Guide This guide goes beyond the [components](./components) and [hooks](./hooks) reference and shows how to wire `@authorizerdev/authorizer-react` into a real application: protecting routes, calling your backend with the access token, rendering UI by role, and integrating with Next.js. All patterns build on the `AuthorizerProvider` + `useAuthorizer()` pair — set up the provider once near the root, then read `user`, `token`, and `loading` anywhere below it. ### Provider setup Wrap your app in `AuthorizerProvider` and import the stylesheet once: ```jsx import { AuthorizerProvider } from '@authorizerdev/authorizer-react'; import '@authorizerdev/authorizer-react/styles.css'; export default function Root({ children }) { return ( { // Fires on every auth-state change — good place to sync // analytics, external stores, etc. console.log('auth state changed', { user, token }); }} > {children} ); } ``` The provider fetches the server's feature flags from `/meta` and automatically refreshes the access token before it expires, so `useAuthorizer()` always reflects the live session. ### Protecting routes Read `token` and `loading` from the hook and branch on them. While the provider is restoring the session, `loading` is `true` — render a spinner, not your login screen, to avoid a flash. ```jsx import { Routes, Route } from 'react-router-dom'; import { useAuthorizer, Authorizer } from '@authorizerdev/authorizer-react'; import Dashboard from './Dashboard'; function App() { const { token, loading } = useAuthorizer(); if (loading) return

Loading…

; if (!token) { return console.log('logged in', data)} />; } return ( } /> ); } ``` For a reusable guard component: ```jsx function RequireAuth({ children }) { const { token, loading } = useAuthorizer(); if (loading) return

Loading…

; if (!token) return ; return children; } // ``` ### Calling your backend with the token The `token` object exposes `access_token` (and `id_token`, `refresh_token`). Attach it as a bearer credential on your API calls: ```jsx import { useAuthorizer } from '@authorizerdev/authorizer-react'; function useApi() { const { token } = useAuthorizer(); return async function api(path, options = {}) { const res = await fetch(`https://api.example.com${path}`, { ...options, headers: { ...options.headers, 'Content-Type': 'application/json', Authorization: token ? `Bearer ${token.access_token}` : '', }, }); if (!res.ok) throw new Error(`API ${res.status}`); return res.json(); }; } ``` Your backend validates that token with Authorizer's [`validate_jwt_token`](../../core/graphql-api#validate_jwt_token) (or the JWKS at `/.well-known/jwks.json`). #### Permission-aware UI with FGA If you use [fine-grained authorization](../../core/authorization), ask the server what the user can do via the [REST](../../core/rest-api#post-v1check_permissions) or [GraphQL](../../core/graphql-api#check_permissions) `check_permissions` endpoint, using the same bearer token, and render accordingly: ```jsx const api = useApi(); const { results } = await api('/v1/check_permissions', { method: 'POST', body: JSON.stringify({ checks: [{ relation: 'can_edit', object: 'document:1' }], }), }); const canEdit = results[0]?.allowed; // {canEdit && } ``` ### Rendering UI by role `user.roles` holds the roles assigned at signup/login. Gate UI on it: ```jsx import { useAuthorizer } from '@authorizerdev/authorizer-react'; function AdminPanel() { const { user } = useAuthorizer(); const isAdmin = user?.roles?.includes('admin'); if (!isAdmin) return null; return
{/* admin-only UI */}
; } ``` You can also restrict which roles a login grants by passing `roles` to the auth components, e.g. ``. ### Logout `useAuthorizer()` returns a `logout` function that clears the session both server-side and in context: ```jsx function LogoutButton() { const { logout } = useAuthorizer(); return ; } ``` ### Multi-factor authentication and passkeys `Authorizer` (and the individual `AuthorizerSignup` / `AuthorizerBasicAuthLogin` / `AuthorizerPasskeyLogin` components) already handle MFA end-to-end during login and signup: when the backend offers or requires a second factor, they automatically render the setup, verification, or locked-account screens for you — no extra wiring needed. To let a signed-in user manage their own second factors from a "Security settings" page, use [`AuthorizerMFASetup`](./components#authorizermfasetup) and [`AuthorizerPasskeyRegister`](./components#authorizerpasskeyregister) directly: ```jsx import { useAuthorizer, AuthorizerMFASetup, AuthorizerPasskeyRegister, } from '@authorizerdev/authorizer-react'; function SecuritySettings() { const { config } = useAuthorizer(); return ( <>

Two-factor authentication

Passkeys

); } ``` `AuthorizerPasskeyLogin` and passkey verification only render for browsers that support [WebAuthn](https://www.w3.org/TR/webauthn-2/) — there is no backend flag to gate them on, so gate any custom UI you build around them on `isWebauthnSupported()` from `@authorizerdev/authorizer-js` the same way. ### Next.js integration `authorizer-react` is a client-side library — render the provider in a client component and keep it out of server components. #### App Router Create a client-side providers wrapper: ```tsx // app/providers.tsx 'use client'; import { AuthorizerProvider } from '@authorizerdev/authorizer-react'; import '@authorizerdev/authorizer-react/styles.css'; export function Providers({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` Use it in the root layout: ```tsx // app/layout.tsx import { Providers } from './providers'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` Then mark any component that calls `useAuthorizer()` or renders an Authorizer component with `'use client'`. #### Pages Router Wrap your app in `pages/_app.tsx`: ```tsx import type { AppProps } from 'next/app'; import { AuthorizerProvider } from '@authorizerdev/authorizer-react'; import '@authorizerdev/authorizer-react/styles.css'; export default function MyApp({ Component, pageProps }: AppProps) { return ( ); } ``` > For SSR data fetching that needs the user, read the session cookie on the server and > validate it with [`validate_session`](../../core/graphql-api#validate_session) rather > than relying on the client-side context. ### Reset-password page Social and email flows redirect back to your `redirectURL`. For password resets, render `AuthorizerResetPassword` on the route you configured (e.g. `/reset-password`) — it reads the `token` and `redirect_uri` from the URL automatically: ```jsx import { AuthorizerResetPassword } from '@authorizerdev/authorizer-react'; export default function ResetPasswordPage() { return (window.location.href = '/')} />; } ``` ### See also - [Components](./components) — every prop of every Authorizer component. - [Hooks](./hooks) — the full `useAuthorizer()` return shape. - [authorizer-js](../authorizer-js/) — the underlying JS SDK (`authorizerRef`) for advanced calls. --- ## Components (Authorizer-svelte) `@authorizerdev/authorizer-svelte` exports the few components that you can use in your svelte application. This will help you build authentication and authorization faster for your application. ### Table of contents - [`AuthorizerProvider`](#authorizerprovider) - [`Authorizer`](#authorizer) - [`AuthorizerSignup`](#authorizersignup) - [`AuthorizerBasicAuthLogin`](#authorizerbasicauthlogin) - [`AuthorizerMagicLinkLogin`](#authorizermagiclinklogin) - [`AuthorizerSocialLogin`](#authorizersociallogin) - [`AuthorizerForgotPassword`](#authorizerforgotpassword) - [`AuthorizerResetPassword`](#authorizerresetpassword) - [`AuthorizerVerifyOtp`](#authorizerverifyotp) ### `AuthorizerProvider` `AuthorizerProvider` is the container component that wraps all the Authorizer components. It binds the backend configuration in the app and renders various views accordingly. It exposes global context store called `authorizerContext` which you can subscribe to in your application #### Props - `config`: Object to configure the `authorizer` backend URL, redirect URL and client id. It accepts JSON object with following keys | Key | Type | Description | Required | | --------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------| -------- | | `authorizerURL` | `string` | Authorizer backend URL | `true` | | `redirectURL` | `string` | Frontend application URL or the page where you want to redirect user post login. Default value is `window.location.origin` | `true` | | `client_id` | `string` | Client ID of the application, generated from the Authorizer dashboard | `true` | - `onStateChangeCallback={(newState)=>{}}`: [optional] Async callback that is called whenever context state information changes. #### Sample Usage ```jsx import { AuthorizerProvider } from '@authorizerdev/authorizer-svelte' const App = () => { return ( {}} > ) } ``` ### `Authorizer` A core component that includes: - social logins - signup view - login view - magic link login view - forgot password view Pre configured component that shows various login/signup options based on the backend configurations. Make sure it is used as Child of `AuthorizerProvider`. #### Props It has following optional props as callback events that are triggered via various user events. - `onLogin={(loginResponse)=>{}}`: event called when login form is submitted successfully. - `onMagicLinkLogin={(magicLinkResponse)=>{}}`: event called when magic link login form is submitted successfully. - `onSignup={(signupResponse)=>{}}`: event called when signup form is submitted successfully. - `onForgotPassword={(forgotPasswordResponse)={}}`: called when forgot password form is submitted successfully. - `roles={['user']}`: [optional] list of roles to request for the logged in / signed up user. #### Sample Usage ```jsx import { Authorizer } from '@authorizerdev/authorizer-svelte' const LoginPage = () => { return ( <>

Login / Signup


{}} onMagicLinkLogin={(magicLinkResponse) => {}} onSignup={(signupResponse) => {}} onForgotPassword={(forgotPasswordResponse = {})} /> ) } ``` ### `AuthorizerSignup` A component to render basic authentication singup form. Make sure it is used as Child of `AuthorizerProvider`. #### Props - `onSignup={(response)=>{}}`: event called when signup form is submitted successfully. - `setView={(view)=>{}}`: [optional] callback used internally by `Authorizer` to switch between `Login`/`Signup`/`ForgotPassword` views. Only needed if you are composing your own view switcher. - `urlProps={{ scope: [], redirect_uri: undefined, state: undefined }}`: [optional] object to override the OAuth `scope`, `redirect_uri` and `state` query params used for the signup request. - `roles={['user']}`: [optional] list of roles to request for the signed up user. #### Sample Usage ```jsx import { AuthorizerSignup } from '@authorizerdev/authorizer-svelte' const SignupPage = () => { return ( <>

Signup


{}} /> ) } ``` ### `AuthorizerBasicAuthLogin` A component to render basic authentication login form. Make sure this is used as Child of `AuthorizerProvider`. #### Props - `onLogin={(response)=>{}}`: event called when login form is submitted successfully. - `setView={(view)=>{}}`: [optional] callback used internally by `Authorizer` to switch between `Login`/`Signup`/`ForgotPassword` views. Only needed if you are composing your own view switcher. - `urlProps={{ scope: [], redirect_uri: undefined, state: undefined }}`: [optional] object to override the OAuth `scope`, `redirect_uri` and `state` query params used for the login request. - `roles={['user']}`: [optional] list of roles to request for the logged in user. #### Sample Usage ```jsx import { AuthorizerBasicAuthLogin } from '@authorizerdev/authorizer-svelte' const LoginPage = () => { return ( <>

Login


{}} /> ) } ``` ### `AuthorizerMagicLinkLogin` A component to render magic link login form. Make sure this is used as Child of `AuthorizerProvider`. #### Props - `onMagicLinkLogin={(response)=>{}}`: event called when magic link login form is submitted successfully. - `urlProps={{ state: 'random-string', redirect_uri: undefined }}`: [optional] object to override the `state` and `redirect_uri` query params used for the magic link request. - `roles={['user']}`: [optional] list of roles to request for the logged in user. #### Sample Usage ```jsx import { AuthorizerMagicLinkLogin } from '@authorizerdev/authorizer-svelte' const LoginPage = () => { return ( <>

Login


{}} /> ) } ``` ### `AuthorizerSocialLogin` A component to render list of social media login buttons based on backend configurations. Make sure this is used as Child of `AuthorizerProvider`. #### Props - `urlProps={{ scope: [] }}`: [optional] object to override the OAuth `scope` query param sent with the social login request. - `roles={['user']}`: [optional] list of roles to request for the logged in user. #### Sample Usage ```jsx import { AuthorizerSocialLogin } from '@authorizerdev/authorizer-svelte' const LoginPage = () => { return ( <>

Login / Signup


) } ``` ### `AuthorizerForgotPassword` A component to render forgot password form. Make sure this is used as Child of `AuthorizerProvider`. #### Props - `onForgotPassword={(response)=>{}}`: event called when forgot password form is submitted successfully. - `setView={(view)=>{}}`: [optional] callback used internally by `Authorizer` to switch between `Login`/`Signup`/`ForgotPassword` views. Only needed if you are composing your own view switcher. - `urlProps={{ state: 'random-string', redirect_uri: undefined }}`: [optional] object to override the `state` and `redirect_uri` query params used for the request. #### Sample Usage ```jsx import { AuthorizerForgotPassword } from '@authorizerdev/authorizer-svelte' const ForgotPasswordPage = () => { return ( <>

Forgot Password?


{}} /> ) } ``` ### `AuthorizerResetPassword` A component that can be used to reset the password. This component can be used in the page, which is configured with the backend as `RESET_PASSWORD_URL`, check [environment variables](/core/server-config) for more details. This component validates the token in the URL sent via email to the user and helps resetting the password. #### Props It has following optional prop as callback event that is triggered on form submit. - `onReset={(response) => {}}`: Called when reset form is submitted #### Sample Usage ```jsx import { AuthorizerResetPassword } from '@authorizerdev/authorizer-svelte' const ResetPassword = () => { return ( <>

Reset Password


{}} /> ) } ``` ### `AuthorizerVerifyOtp` A component to render the OTP verification form. Make sure it is used as Child of `AuthorizerProvider`. #### Props - `email="foo@bar.com"`: user email address on which the OTP was sent. It also has following optional props. - `onLogin={(response)=>{}}`: callback event that is triggered when the verify OTP form is submitted successfully. - `setView={(view)=>{}}`: callback used internally by `Authorizer` to switch between `Login`/`Signup`/`ForgotPassword` views. Only needed if you are composing your own view switcher. - `urlProps={{ state: undefined }}`: object to override the `state` query param used for the verify request. #### Sample Usage ```jsx import { AuthorizerVerifyOtp } from '@authorizerdev/authorizer-svelte' const VerifyOtp = () => { return ( <>

Verify OTP


{}} /> ) } ``` --- ## Getting Started (7) Svelte SDK for [authorizer.dev](https://authorizer.dev) integration in your [svelte-js](https://svelte.dev/) application. This will allow you to have authentication and authorization ready in minutes. Here is a quick guide on getting started with `@authorizerdev/authorizer-svelte` package. ### Step 1: Get Authorizer Instance Deploy production ready Authorizer instance using one click deployment options available below | **Infra provider** | **One-click link** | **Additional information** | | :----------------: | :-----------------: | :----------------------------------------------------: | | Railway.app | [Deploy on Railway](https://railway.com/deploy/authorizer-1?referralCode=FEF4uT&utm_medium=integration&utm_source=template&utm_campaign=generic) | [docs](/deployment/railway) | | Heroku | [Deploy to Heroku](https://heroku.com/deploy?template=https://github.com/authorizerdev/authorizer-heroku) | [docs](/deployment/heroku) | | Render | [Deploy to Render](https://render.com/deploy?repo=https://github.com/authorizerdev/authorizer-render) | [docs](/deployment/render) | For more information check [docs](/getting-started/) ### Step 2: Setup Instance Start your Authorizer instance with the required CLI flags: ```bash ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` Note the `--client-id` value -- you will need it in the SDK configuration below. Check [Server Configuration](/core/server-config) for all available flags. ### Step 3 - Install package Assuming you have svelte-js application up and running, install following package in your application ```sh npm i --save @authorizerdev/authorizer-svelte OR yarn add @authorizerdev/authorizer-svelte ``` ### Step 4 - Configure Provider and use Authorizer Components Authorizer comes with global context `authorizerContext` which is available once you have configured `AuthorizerProvider` component. Configure `AuthorizerProvider` at root level in your application and import `default.css`. > Note: You can override default style with `css` variables. Check [docs](/sdks/authorizer-svelte) for more details. `eg: routes/+layout.svelte` ```svelte ``` **Use `Authorizer` Component** `eg: routes/+page.svelte` ```svelte {#if state.user}

Hey,

{state.user.email}
{#if state.loading}

Processing....

{:else}

Logout

{/if}
{:else} {/if} ``` ### Updating styles Components in `@authorizerdev/authorizer-svelte` are designed using css variables and comes with `default.css` which declares this variables. You can modify these css variable to update styling as per your theme: > Note: Given are the default values for the variables. ```css --authorizer-primary-color: #3b82f6; --authorizer-primary-disabled-color: #60a5fa; --authorizer-gray-color: #d1d5db; --authorizer-white-color: #ffffff; --authorizer-danger-color: #dc2626; --authorizer-success-color: #10b981; --authorizer-text-color: #374151; --authorizer-fonts-font-stack: -apple-system, system-ui, sans-serif; --authorizer-fonts-large-text: 18px; --authorizer-fonts-medium-text: 14px; --authorizer-fonts-small-text: 12px; --authorizer-fonts-tiny-text: 10px; --authorizer-radius-card: 5px; --authorizer-radius-button: 5px; --authorizer-radius-input: 5px; ``` ### Examples Please check the [example repo](https://github.com/authorizerdev/examples) to see how to use this component library. --- ## Getting Started (8) Vue 3 SDK for [authorizer.dev](https://authorizer.dev) integration in your [Vue](https://vuejs.org/) application. This will allow you to have authentication and authorization ready in minutes. Here is a quick guide on getting started with `@authorizerdev/authorizer-vue` package. ### Step 1: Get Authorizer Instance Deploy production ready Authorizer instance using one click deployment options available below | **Infra provider** | **One-click link** | **Additional information** | | :----------------: | :-----------------: | :----------------------------------------------------: | | Railway.app | [Deploy on Railway](https://railway.com/deploy/authorizer-1?referralCode=FEF4uT&utm_medium=integration&utm_source=template&utm_campaign=generic) | [docs](/deployment/railway) | | Heroku | [Deploy to Heroku](https://heroku.com/deploy?template=https://github.com/authorizerdev/authorizer-heroku) | [docs](/deployment/heroku) | | Render | [Deploy to Render](https://render.com/deploy?repo=https://github.com/authorizerdev/authorizer-render) | [docs](/deployment/render) | For more information check [docs](/getting-started/) ### Step 2: Setup Instance Start your Authorizer instance with the required CLI flags: ```bash ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` Note the `--client-id` value -- you will need it in the SDK configuration below. Check [Server Configuration](/core/server-config) for all available flags. ### Step 3 - Install package Assuming you have a Vue 3 application up and running, install the following package in your application ```sh npm i --save @authorizerdev/authorizer-vue OR yarn add @authorizerdev/authorizer-vue ``` ### Step 4 - Configure Provider and use Authorizer Components `AuthorizerProvider` uses Vue's [provide/inject](https://vuejs.org/api/composition-api-dependency-injection.html#provide) to make a reactive auth context available to all descendants via the `useAuthorizer` injection key. Configure `AuthorizerProvider` at the root of your application and import `default.css`. > Note: You can override default style with `css` variables. See [Updating styles](#updating-styles) below for more details. `eg: App.vue` ```vue ``` **Use `AuthorizerRoot` Component** `eg: views/Login.vue` ```vue ``` ### Components `@authorizerdev/authorizer-vue` exports the following components that you can use in your Vue application to build authentication and authorization faster: - [`AuthorizerProvider`](#authorizerprovider) - [`AuthorizerRoot`](#authorizerroot) - [`AuthorizerSignup`](#authorizersignup) - [`AuthorizerBasicAuthLogin`](#authorizerbasicauthlogin) - [`AuthorizerMagicLinkLogin`](#authorizermagiclinklogin) - [`AuthorizerSocialLogin`](#authorizersociallogin) - [`AuthorizerForgotPassword`](#authorizerforgotpassword) - [`AuthorizerResetPassword`](#authorizerresetpassword) - [`AuthorizerVerifyOtp`](#authorizerverifyotp) #### `AuthorizerProvider` `AuthorizerProvider` is the container component that wraps all the Authorizer components. It binds the backend configuration in the app and renders various views accordingly. It exposes a reactive context via the `useAuthorizer` provide/inject key, which you can `inject` in any descendant component. ##### Props | Prop | Type | Required | Description | | ----------------------- | ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------| | `config` | `AuthorizerConfigInput` | Yes | Authorizer connection config (see below) | | `onStateChangeCallback` | `(state: AuthorizerState) => void` | No | [optional] Callback that is called whenever context state information changes. | `config` accepts the following keys: | Key | Type | Description | Required | | -------------- | ------------------------| ----------------------------------------------------------------------------------------------------------------------------| -------- | | `authorizerURL`| `string` | Authorizer backend URL | `true` | | `redirectURL` | `string` | Frontend application URL or the page where you want to redirect user post login. Default value is `window.location.origin` | `true` | | `clientID` | `string` | Client ID of the application, generated from the Authorizer dashboard | `true` | | `protocol` | `'graphql' \| 'rest'` | [optional] Transport protocol used by the underlying `authorizer-js` SDK. Defaults to `'graphql'` | `false` | ##### Sample Usage ```vue ``` #### `AuthorizerRoot` A core component that includes: - social logins - signup view - login view - magic link login view - forgot password view Pre configured component that shows various login/signup options based on the backend configurations. Make sure it is used as a descendant of `AuthorizerProvider`. ##### Props It has the following optional props as callback events that are triggered via various user events, plus a `roles` prop. - `onLogin`: event called when login form is submitted successfully. - `onSignup`: event called when signup form is submitted successfully. - `onMagicLinkLogin`: event called when magic link login form is submitted successfully. - `onForgotPassword`: event called when forgot password form is submitted successfully. - `roles`: [optional] `string[]` list of roles to request for the logged in / signed up user. ##### Sample Usage ```vue ``` #### `AuthorizerSignup` A component to render the basic authentication signup form. Make sure it is used as a descendant of `AuthorizerProvider`. ##### Props - `onSignup`: event called when signup form is submitted successfully. - `setView`: [optional] callback used internally by `AuthorizerRoot` to switch between `Login`/`Signup`/`ForgotPassword` views. Only needed if you are composing your own view switcher. - `urlProps`: [optional] object to override the `scope`, `redirect_uri` and `state` query params used for the signup request. - `roles`: [optional] `string[]` list of roles to request for the signed up user. ##### Sample Usage ```vue ``` #### `AuthorizerBasicAuthLogin` A component to render the basic authentication login form. Make sure it is used as a descendant of `AuthorizerProvider`. ##### Props - `onLogin`: event called when login form is submitted successfully. - `setView`: [optional] callback used internally by `AuthorizerRoot` to switch between `Login`/`Signup`/`ForgotPassword` views. Only needed if you are composing your own view switcher. - `urlProps`: [optional] object to override the `scope`, `redirect_uri` and `state` query params used for the login request. - `roles`: [optional] `string[]` list of roles to request for the logged in user. ##### Sample Usage ```vue ``` #### `AuthorizerMagicLinkLogin` A component to render the magic link login form. Make sure it is used as a descendant of `AuthorizerProvider`. ##### Props - `onMagicLinkLogin`: event called when magic link login form is submitted successfully. - `urlProps`: [optional] object to override the `redirect_uri` and `state` query params used for the request. - `roles`: [optional] `string[]` list of roles to request for the logged in user. ##### Sample Usage ```vue ``` #### `AuthorizerSocialLogin` A component to render the list of social media login buttons based on backend configurations. Supports Google, GitHub, Facebook, LinkedIn, Apple, Twitter, Microsoft, Discord and Roblox. Make sure it is used as a descendant of `AuthorizerProvider`. ##### Props - `urlProps`: [optional] object to override the `scope` query param sent with the social login request. - `roles`: [optional] `string[]` list of roles to request for the logged in user. ##### Sample Usage ```vue ``` #### `AuthorizerForgotPassword` A component to render the forgot password form. Make sure it is used as a descendant of `AuthorizerProvider`. ##### Props - `onForgotPassword`: event called when forgot password form is submitted successfully. - `setView`: [optional] callback used internally by `AuthorizerRoot` to switch between `Login`/`Signup`/`ForgotPassword` views. Only needed if you are composing your own view switcher. - `urlProps`: [optional] object to override the `redirect_uri` and `state` query params used for the request. ##### Sample Usage ```vue ``` #### `AuthorizerResetPassword` A component that can be used to reset the password. This component can be used on the page which is configured with the backend as `RESET_PASSWORD_URL`, check [environment variables](/core/server-config) for more details. This component validates the token in the URL sent via email to the user and helps reset the password. ##### Props - `onReset`: [optional] event called when the reset form is submitted successfully. ##### Sample Usage ```vue ``` #### `AuthorizerVerifyOtp` A component to render the OTP verification form. Make sure it is used as a descendant of `AuthorizerProvider`. ##### Props - `email`: (required) user email address on which the OTP was sent. - `onLogin`: [optional] event called when the verify OTP form is submitted successfully. - `setView`: [optional] callback used internally by `AuthorizerRoot` to switch between `Login`/`Signup`/`ForgotPassword` views. Only needed if you are composing your own view switcher. - `urlProps`: [optional] object to override the `state` query param used for the verify request. ##### Sample Usage ```vue ``` ### Updating styles Components in `@authorizerdev/authorizer-vue` are designed using css variables and come with a default stylesheet which declares these variables. You can override these css variables to update styling as per your theme: > Note: Given are the default values for the variables. ```css --authorizer-primary-color: #3b82f6; --authorizer-primary-disabled-color: #60a5fa; --authorizer-gray-color: #d1d5db; --authorizer-white-color: #ffffff; --authorizer-danger-color: #dc2626; --authorizer-success-color: #10b981; --authorizer-text-color: #374151; --authorizer-fonts-font-stack: -apple-system, system-ui, sans-serif; --authorizer-fonts-large-text: 18px; --authorizer-fonts-medium-text: 14px; --authorizer-fonts-small-text: 12px; --authorizer-fonts-tiny-text: 10px; --authorizer-radius-card: 5px; --authorizer-radius-button: 5px; --authorizer-radius-input: 5px; ``` ### Examples Please check the [example repo](https://github.com/authorizerdev/examples) to see how to use this component library. --- ## Alibaba Cloud ## Deploy on Alibaba Cloud ### Introduction Deploy a ready-to-use Authorizer instance on [Alibaba Cloud](https://www.alibabacloud.com/) using the **Alibaba Cloud Compute Nest** service. ### Requirements An [Alibaba Cloud account](https://www.alibabacloud.com/). ### One-click Deploy [![Deploy on Alibaba Cloud](https://service-info-public.oss-cn-hangzhou.aliyuncs.com/computenest-en.svg)](https://computenest.console.aliyun.com/service/instance/create/default?type=user&ServiceName=Authorizer%E7%A4%BE%E5%8C%BA%E7%89%88) 1. Select parameters for the type of ECS to deploy 2. Choose to create a new dedicated network or use an existing one 3. Click **Create Now** and wait for the service instance to be deployed ### Configure for v2 After deployment, configure the required v2 variables in your instance: ```bash ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=https://auth.example.com \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` --- ## Binary Deployment ## Binary (v2) This guide shows how to run the **Authorizer v2 binary** in environments where you download or build the binary yourself. Unlike v1, **all configuration is passed as CLI flags** -- the server does not read `.env` files or dashboard-managed env. If you are migrating from v1, compare with the original [Binary](../deployment/binary) page and the [Migration v1 to v2](../migration/v1-to-v2) guide. --- ### 1. Download or build the v2 binary Releases publish the [Docker image](./docker), not prebuilt binaries, so build from source (Go and Node.js required): ```bash git clone https://github.com/authorizerdev/authorizer.git cd authorizer go build -o build/authorizer . make build-app build-dashboard # login UI and admin dashboard ``` Run the binary from the repository root (or copy `build/authorizer` together with the `web/` directory): the login UI, dashboard and email templates are loaded from `web/` relative to the working directory. --- ### 2. Decide your CLI configuration At minimum, Authorizer v2 needs: - Database configuration. - `--client-id` and `--client-secret`. - Admin and JWT configuration. Example for SQLite: ```bash ./authorizer \ --env=production \ --http-port=8080 \ --database-type=sqlite \ --database-url=data.db \ --url=https://auth.example.com \ --client-id=YOUR_CLIENT_ID \ --client-secret=YOUR_CLIENT_SECRET \ --admin-secret=your-admin-secret \ --jwt-type=HS256 \ --jwt-secret=your-jwt-secret \ --encryption-key=your-encryption-key ``` > **Note:** In v2, flags such as `database_url`, `env_file`, and dashboard mutations like `_update_env` are **deprecated** -- use the `kebab-case` flags above instead. For more options (Redis, SMTP, social providers, etc.), see [Server Configuration (v2)](../core/server-config). --- ### 3. Running the binary in production You can still use process managers like `systemd`, but instead of relying on `.env`, configure the **ExecStart** with CLI flags. Example `systemd` service file: ```ini [Unit] Description=Authorizer v2 [Service] Type=simple Restart=always RestartSec=5 ExecStart=/path_to_authorizer_parent_folder/authorizer/build/authorizer \ --env=production \ --http-port=8080 \ --database-type=postgres \ --database-url=${DATABASE_URL} \ --url=https://auth.example.com \ --client-id=${CLIENT_ID} \ --client-secret=${CLIENT_SECRET} \ --admin-secret=${ADMIN_SECRET} \ --jwt-type=RS256 \ --jwt-private-key=${JWT_PRIVATE_KEY} \ --jwt-public-key=${JWT_PUBLIC_KEY} \ --encryption-key=${ENCRYPTION_KEY} WorkingDirectory=/path_to_authorizer_parent_folder/authorizer/ Environment=DATABASE_URL=postgres://user:pass@host/db Environment=CLIENT_ID=your-client-id Environment=CLIENT_SECRET=your-client-secret Environment=ADMIN_SECRET=your-admin-secret Environment=JWT_PRIVATE_KEY=... Environment=JWT_PUBLIC_KEY=... Environment=ENCRYPTION_KEY=generate-with-openssl-rand-hex-32 [Install] WantedBy=multi-user.target ``` Then: ```bash sudo systemctl daemon-reload sudo systemctl restart authorizer ``` This pattern lets your platform manage secrets as **env vars**, while Authorizer still receives them **only as CLI flags**, which is the v2 model. --- ## Docker Run Authorizer using Docker with the v2 **CLI-only configuration model**. --- ### Quick Start ```bash docker run -p 8080:8080 quay.io/authorizer/authorizer:latest \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` #### Persisting data across restarts The command above writes `test.db` inside the container, so **every restart starts from an empty database**. Mount a named volume at `/authorizer/data` and put SQLite on it: ```bash docker run -p 8080:8080 \ -v authorizer_data:/authorizer/data \ quay.io/authorizer/authorizer \ --database-type=sqlite \ --database-url=/authorizer/data/data.db \ --url=http://localhost:8080 \ --client-id=123456 \ --client-secret=secret \ --admin-secret=admin \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key ``` The image runs as uid 1000 (`authorizer`). From **v2.4.9**, the image creates `/authorizer/data` owned by that user. A named volume mounted there takes on that ownership, so the command above works without extra flags. This only applies at exactly `/authorizer/data`. A volume mounted at any other path is still created owned by root. **Images older than v2.4.9** don't have that directory, so the volume is created owned by root and the process can't create the database file. Add `-u root`: ```bash docker run -p 8080:8080 -u root \ -v authorizer_data:/authorizer/data \ quay.io/authorizer/authorizer: \ --database-type=sqlite \ --database-url=/authorizer/data/data.db \ ... ``` You can also `chown` the volume to uid 1000 once, or use a managed database instead. **Docker Compose.** The server repository's [`docker-compose.yaml`](https://github.com/authorizerdev/authorizer/blob/main/docker-compose.yaml) is a quick way to run Authorizer locally. It builds the image from source and configures everything with CLI flags. It stores SQLite at `/authorizer/data/authorizer.db` on the `authorizer_data` named volume, and publishes ports `8080` (HTTP) and `9091` (gRPC). Every secret in it is a placeholder, so it is for local development and evaluation only: ```bash git clone https://github.com/authorizerdev/authorizer.git cd authorizer docker compose up --build ``` Then open `http://localhost:8080/app` for the built-in login UI. --- ### Ports: `EXPOSE`, publishing, and metrics {#docker-ports-exposure} The image **`EXPOSE`s `8080`, `8081`, and `9091`**. That only **documents** which ports the application may listen on; it does **not** open them on the Docker host. You choose what to publish with `-p` or Compose `ports:`. | Port | Role | Typical use | |------|------|-------------| | **8080** | Main HTTP (API, UI, `/healthz`, `/readyz`) | **Yes** — map to the host or front with a reverse proxy / load balancer. | | **8081** | [Prometheus](https://prometheus.io) **`/metrics`** (separate listener) | **Depends** — see below. | | **9091** | **gRPC** API (`AuthorizerService` + `AuthorizerAdminService`) | **Optional** — publish only if external gRPC clients connect; see [gRPC API](../core/grpc). | **Recommended defaults** - **`docker run` (single container, no in-Docker Prometheus):** publish **only `8080`** (e.g. `-p 8080:8080`). Metrics stay on **`127.0.0.1:8081`** inside the container; that is enough if you scrape from an agent on the **same host** using the container’s network namespace, or you do not need metrics yet. - **Docker Compose / Swarm with Prometheus as another service:** add **`--metrics-host=0.0.0.0`** so `8081` accepts connections on the **internal** compose network. Prefer **not** adding `"8081:8081"` under `ports:` (avoids exposing metrics on the host). Prometheus should use a service DNS name like `http://authorizer:8081/metrics` on the internal network only. - **gRPC clients:** the gRPC server binds to `--host` (default `0.0.0.0`) on **`9091`**. For server-to-server calls **on the same Docker/Compose network**, dial the service name (e.g. `authorizer:9091`) — no host publishing needed. Only add `-p 9091:9091` (or `"9091:9091"` under `ports:`) when a client **outside** Docker must reach it. gRPC is served as plaintext h2c by default — terminate TLS at an ingress/proxy (or set `--grpc-tls-cert` / `--grpc-tls-key`) before exposing it publicly. - **Public internet:** never publish **8081** to a public address. Keep metrics on loopback or an internal network; use auth/network policy at the edge if you must expose a scrape path. **Health checks:** the image `HEALTHCHECK` calls **`http://127.0.0.1:8080/healthz`** on the main server only, so liveness works even when metrics are loopback-only. --- ### Using with PostgreSQL ```bash docker run -p 8080:8080 quay.io/authorizer/authorizer:latest \ --database-type=postgres \ --database-url="postgres://user:pass@host:5432/authorizer" \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=your-jwt-secret \ --encryption-key=test-encryption-key \ --admin-secret=your-admin-secret \ --client-id=123456 \ --client-secret=secret ``` --- ### Docker Compose Create a `docker-compose.yml`: ```yaml services: authorizer: image: quay.io/authorizer/authorizer:latest ports: - "8080:8080" command: - "--database-type=sqlite" - "--database-url=/authorizer/data/data.db" - "--url=http://localhost:8080" - "--jwt-type=HS256" - "--jwt-secret=test" - "--encryption-key=test-encryption-key" - "--admin-secret=admin" - "--client-id=123456" - "--client-secret=secret" volumes: # Must be /authorizer/data: on v2.4.9+ images that directory is owned by # the non-root user, so the volume is writable without `user: root`. # On older images add `user: root` (see "Persisting data" above). - authorizer_data:/authorizer/data volumes: authorizer_data: ``` Start with: ```bash docker compose up -d ``` --- ### Docker Compose with PostgreSQL and Redis ```yaml version: "3.8" services: postgres: image: postgres:15 environment: POSTGRES_USER: authorizer POSTGRES_PASSWORD: secret POSTGRES_DB: authorizer volumes: - pg_data:/var/lib/postgresql/data redis: image: redis:7-alpine ports: - "6379:6379" authorizer: image: quay.io/authorizer/authorizer:latest ports: - "8080:8080" depends_on: - postgres - redis command: - "--database-type=postgres" - "--database-url=postgres://authorizer:secret@postgres:5432/authorizer" - "--url=http://localhost:8080" - "--redis-url=redis://redis:6379" - "--jwt-type=HS256" - "--jwt-secret=test" - "--encryption-key=test-encryption-key" - "--admin-secret=admin" - "--client-id=123456" - "--client-secret=secret" - "--env=production" volumes: pg_data: ``` --- ### Using Environment Variables with v2 The v2 server does **not** read from `.env` files or OS env vars directly. To use env vars in your deployment, map them into CLI flags: ```bash docker run -p 8080:8080 \ -e DATABASE_TYPE=sqlite \ -e DATABASE_URL=test.db \ -e JWT_SECRET=test \ -e ENCRYPTION_KEY=test-encryption-key \ -e ADMIN_SECRET=admin \ -e CLIENT_ID=123456 \ -e CLIENT_SECRET=secret \ quay.io/authorizer/authorizer:latest \ --database-type="$DATABASE_TYPE" \ --database-url="$DATABASE_URL" \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret="$JWT_SECRET" \ --encryption-key="$ENCRYPTION_KEY" \ --admin-secret="$ADMIN_SECRET" \ --client-id="$CLIENT_ID" \ --client-secret="$CLIENT_SECRET" ``` --- ### Required Variables | Flag | Description | Example | | ---- | ----------- | ------- | | `--database-type` | Database type | `sqlite`, `postgres`, `mysql` | | `--database-url` | Database connection string | `test.db` | | `--url` | This server's own public base URL **(required)** | `https://auth.example.com` | | `--jwt-type` | JWT signing algorithm | `HS256`, `RS256` | | `--jwt-secret` | JWT signing secret (for HS256) | `test` | | `--admin-secret` | Admin secret for admin operations | `admin` | | `--client-id` | Client identifier **(required)** | `123456` | | `--client-secret` | Client secret **(required)** | `secret` | For all available flags, see [Server Configuration](../core/server-config). --- ## EasyPanel ## Deploy on EasyPanel ### Introduction [EasyPanel](https://easypanel.io) is a modern server control panel that helps you deploy applications on your own server. ### Deploy an Authorizer Instance EasyPanel provides a template for deploying Authorizer. Deploy using the template: 1. Login to your EasyPanel dashboard 2. Search for the **Authorizer** template 3. Click **Deploy** ### Configure for v2 After deployment, update the start command to include the required v2 CLI flags: ```bash ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=https://your-app.easypanel.host \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` | Variable | Example Value | | -------- | ------------- | | `--database-type` | `sqlite` | | `--database-url` | `test.db` | | `--jwt-type` | `HS256` | | `--jwt-secret` | `test` | | `--encryption-key` | *(generate once with `openssl rand -hex 32`)* | | `--admin-secret` | `admin` | | `--client-id` | `123456` | | `--client-secret` | `secret` | ### Update Instance Update the Docker image version in your EasyPanel configuration to the desired version from [GitHub Releases](https://github.com/authorizerdev/authorizer/releases) or [Quay](https://quay.io/repository/authorizer/authorizer). --- ## Fly.io ## Deploy on Fly.io ### Introduction [Fly.io](https://fly.io) is a platform for running full-stack apps and databases close to your users. It also provides custom domain configuration and free SSL via the CLI. ### Requirements - A [Fly account](https://fly.io) - [Fly CLI](https://fly.io/docs/app-guides/run-a-private-dns-over-https-service/#install-fly-cli) ### Deploy an Authorizer Instance #### Step 1: Login to Fly.io ```bash flyctl auth login ``` #### Step 2: Create Fly.io app ```bash mkdir authorizer-fly cd authorizer-fly flyctl launch --no-deploy ``` Follow the wizard to set the application name, region, etc. ![Fly.io launch](/img/fly-01.png) #### Step 3: Setup Postgres instance ```bash flyctl postgres create --password ``` Choose `Development` configuration for a free instance. ![Fly.io Postgres](/img/fly-02.png) Attach Postgres to your app: ```bash flyctl postgres attach ``` #### Step 4: Setup Redis instance (optional) Follow the [official Redis documentation](https://fly.io/docs/reference/redis/). #### Step 5: Configure `fly.toml` ```toml app = "authorizer" kill_signal = "SIGINT" kill_timeout = 5 processes = [] [build] image = "quay.io/authorizer/authorizer:latest" [experimental] cmd = [ "./authorizer", "--database-type=postgres", "--database-url=postgres://user:pass@localhost:5432/authorizer", "--url=https://authorizer.fly.dev", "--jwt-type=HS256", "--jwt-secret=test", "--encryption-key=$ENCRYPTION_KEY", "--admin-secret=admin", "--client-id=123456", "--client-secret=secret" ] private_network = true auto_rollback = true [env] PORT = "8080" [[services]] internal_port = 8080 processes = ["app"] protocol = "tcp" [services.concurrency] type = "connections" hard_limit = 25 soft_limit = 20 [[services.ports]] force_https = true handlers = ["http"] port = 80 [[services.ports]] handlers = ["tls", "http"] port = 443 [[services.tcp_checks]] grace_period = "1s" interval = "15s" restart_limit = 0 timeout = "2s" ``` #### Step 6: Configure secrets ```bash flyctl secrets set \ DATABASE_TYPE="postgres" \ JWT_TYPE="HS256" \ JWT_SECRET="your-jwt-secret" \ ENCRYPTION_KEY="your-encryption-key" \ ADMIN_SECRET="your-admin-secret" \ CLIENT_ID="123456" \ CLIENT_SECRET="secret" \ SMTP_HOST="smtp.example.com" \ SMTP_PORT="587" \ SMTP_USERNAME="user@example.com" \ SMTP_PASSWORD="strong-password" \ SMTP_SENDER_EMAIL="auth@example.com" ``` Then update the `cmd` in `fly.toml` to reference secrets as env vars passed to CLI flags. #### Step 7: Deploy ```bash flyctl deploy ``` Check logs: ```bash flyctl logs ``` ### Update Instance Redeploy with `flyctl deploy` inside the directory containing `fly.toml`. ### Custom Domain and SSL See the [Fly.io custom domain docs](https://fly.io/docs/app-guides/custom-domains-with-fly/). --- ## Helm Chart Install Authorizer on a Kubernetes cluster using the official Helm chart. --- ### Prerequisites - A running Kubernetes cluster - [Helm](https://helm.sh/docs/intro/install/) installed --- ### Getting Started #### Step 1: Add repository ```bash helm repo add authorizer https://helm-charts.authorizer.dev ``` #### Step 2: Update helm repos ```bash helm repo update ``` #### Step 3: Install helm chart For a minimal setup with SQLite and the required v2 variables: ```bash helm install \ --namespace authorizer \ --create-namespace \ --set authorizer.database_type=sqlite \ --set authorizer.database_url="/tmp/test.db" \ --set authorizer.authorizer_url=https://auth.example.com \ --set authorizer.jwt_type=HS256 \ --set authorizer.jwt_secret=test \ --set authorizer.encryption_key=test-encryption-key \ --set authorizer.admin_secret=admin \ --set authorizer.client_id=123456 \ --set authorizer.client_secret=secret \ --set securityContext.readOnlyRootFilesystem=false \ authorizer authorizer/authorizer ``` For PostgreSQL: ```bash helm install \ --namespace authorizer \ --create-namespace \ --set authorizer.database_type=postgres \ --set authorizer.database_url="postgres://user:pass@host:5432/authorizer" \ --set authorizer.authorizer_url=https://auth.example.com \ --set authorizer.jwt_type=HS256 \ --set authorizer.jwt_secret=your-jwt-secret \ --set authorizer.encryption_key=your-encryption-key \ --set authorizer.admin_secret=your-admin-secret \ --set authorizer.client_id=123456 \ --set authorizer.client_secret=secret \ authorizer authorizer/authorizer ``` --- ### Helm Chart Variables #### Required Variables | Name | Description | Default | | ---- | ----------- | ------- | | `authorizer.database_type` | Database type: `postgres`, `yugabyte`, `cockroachdb`, `serenedb`, `surrealdb`, `mysql`, `mariadb`, `planetscale`, `sqlite`, `libsql`, `sqlserver`, `mongodb`, `arangodb`, `cassandradb`, `scylladb`, `couchbase`, `dynamodb` | - | | `authorizer.database_url` | Database connection string. See [Databases](../core/databases) | - | | `authorizer.authorizer_url` | This deployment's own public base URL, with the scheme (`--url`). **Required as of 2.4.0** — the chart refuses to render without it, because the server exits at boot. This is *not* `allowed_origins`: `authorizer_url` is where Authorizer itself is reachable, `allowed_origins` lists the apps it may redirect to | - | | `authorizer.client_id` | Client identifier **(required in v2)** | - | | `authorizer.client_secret` | Client secret **(required in v2)** | - | | `authorizer.admin_secret` | Admin secret for admin operations | - | | `authorizer.jwt_type` | JWT signing algorithm (`HS256`, `RS256`) | - | | `authorizer.jwt_secret` | JWT signing secret (for HS256) | - | #### Database Variables | Name | Description | Default | | ---- | ----------- | ------- | | `authorizer.database_host` | Host name for cassandradb and scylladb | - | | `authorizer.database_username` | Username for cassandradb and scylladb | - | | `authorizer.database_password` | Password for cassandradb and scylladb | - | | `authorizer.database_cert` | SSL Certificate (base64 encoded) for cassandradb and scylladb | - | | `authorizer.database_cert_key` | SSL Certificate Key (base64 encoded) for cassandradb and scylladb | - | | `authorizer.database_ca_cert` | CA Signed Certificate (base64 encoded) for cassandradb and scylladb | - | | `authorizer.aws_region` | AWS Region for DynamoDB | - | | `authorizer.aws_access_key_id` | AWS access key identifier for DynamoDB | - | | `authorizer.aws_secret_access_key` | AWS secret access key for DynamoDB | - | #### Redis / Session Store | Name | Description | Default | | ---- | ----------- | ------- | | `authorizer.redis_url` | Redis connection string for session storage | - | | `redis.install` | Install Redis (`true`/`false`) | - | | `redis.storageClassName` | Storage class name for Redis PVC | - | | `redis.storage` | Size of Redis PVC | `5Gi` | #### HTTP, metrics, and rate limiting | Name | Description | Default | | ---- | ----------- | ------- | | `authorizer.http_port` | Main HTTP listen port (`--http-port`); must differ from `metrics_port` | `8080` | | `authorizer.metrics_port` | Dedicated `/metrics` listener port (`--metrics-port`) | `8081` | | `authorizer.metrics_host` | Bind address for `/metrics` (`--metrics-host`); `0.0.0.0` for in-cluster [Prometheus](https://prometheus.io) | `0.0.0.0` | | `authorizer.rate_limit_rps` | Per-IP sustained RPS (`--rate-limit-rps`); `0` disables | `30` | | `authorizer.rate_limit_burst` | Per-IP burst size (`--rate-limit-burst`) | `20` | | `authorizer.rate_limit_fail_closed` | On Redis/rate-limit errors, return 503 (`--rate-limit-fail-closed`) | `false` | #### Redirect URIs and origins | Name | Description | Default | | ---- | ----------- | ------- | | `authorizer.allowed_origins` | Comma-separated origins allowed to call this server (`--allowed-origins`) | `*` | | `authorizer.redirect_uris` | Comma-separated list of **exact** redirect URIs for this deployment's own client (`--redirect-uris`, new in 2.4.0). When unset, `redirect_uri` falls back to matching `allowed_origins`, which compares *origins* — any path under an allowed host is accepted. See [server config](../core/server-config) | - | :::warning `redirect_uris` applies to every flow carrying this `client_id` It is not a per-app setting. List every callback your apps use, including local development ones, or those logins are refused with `invalid redirect_uri`. ::: #### Couchbase | Name | Description | Default | | ---- | ----------- | ------- | | `authorizer.couchbase_bucket` | Couchbase bucket for authorizer collections | `authorizer` | | `authorizer.couchbase_bucket_ram_quota` | Couchbase bucket RAM quota in MB | `1000` | | `authorizer.couchbase_scope` | Couchbase scope for authorizer collections | `_default` | --- ### Upgrading To upgrade to a newer version of the Helm chart: ```bash helm repo update helm upgrade authorizer authorizer/authorizer --namespace authorizer ``` --- ### How the chart configures the container Chart `2.x` passes every `authorizer.*` value to the container as a `--kebab-case` CLI flag, matching the v2 CLI-only configuration model. There is no `.env` file to mount and no `_update_env` dashboard call. - Secrets (`client_secret`, `jwt_secret`, `admin_secret`, database credentials, every social-provider secret) are written to Kubernetes `Secret` resources and injected as environment variables, which the container's entrypoint expands into the flags. They never appear in the pod spec's `args`. - Non-secret values are rendered into the args directly. - A value left `null` is omitted, so the server's own default applies. Run `helm show values authorizer/authorizer` for the full list — each key is documented in place, and maps to the flag of the same name in [Server configuration](../core/server-config). --- ## Heroku ## Deploy on Heroku ### Create Instance Deploy Authorizer with PostgreSQL on [Heroku](https://heroku.com): [![Deploy to Heroku](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/authorizerdev/authorizer-heroku) After clicking the button: #### Step 1: Enter the App name The app name becomes your URL. For example, `authorizer-demo` gives you `authorizer-demo.herokuapp.com`. #### Step 2: Choose the Region and deploy Select your deployment region (United States or Europe). #### Step 3: Configure for v2 For Authorizer v2, configure the following required variables in your Heroku app settings under **Config Vars**: | Variable | Example Value | | -------- | ------------- | | `DATABASE_TYPE` | `postgres` | | `DATABASE_URL` | *(auto-configured by Heroku add-on)* | | `JWT_TYPE` | `HS256` | | `JWT_SECRET` | `test` | | `ENCRYPTION_KEY` | *(generate once with `openssl rand -hex 32`)* | | `ADMIN_SECRET` | `admin` | | `CLIENT_ID` | `123456` | | `CLIENT_SECRET` | `secret` | | `AUTHORIZER_URL` | `https://your-app.herokuapp.com` *(your public Heroku URL)* | #### Optional: metrics bind address and rate limits The [authorizer-heroku](https://github.com/authorizerdev/authorizer-heroku) Dockerfile passes these **Config Vars** through to the binary (shell defaults match Authorizer): | Variable | Maps to | Default | Notes | | -------- | ------- | ------- | ----- | | `METRICS_HOST` | `--metrics-host` | `127.0.0.1` | `0.0.0.0` only if an internal scraper must reach `METRICS_PORT`; do not publish metrics publicly. | | `METRICS_PORT` | `--metrics-port` | `8081` | | | `RATE_LIMIT_RPS` | `--rate-limit-rps` | `30` | `0` disables per-IP limiting. | | `RATE_LIMIT_BURST` | `--rate-limit-burst` | `20` | | | `RATE_LIMIT_FAIL_CLOSED` | `--rate-limit-fail-closed` | `false` | `true` → **503** on rate-limit backend errors. | Use `REDIS_URL` for shared sessions and rate limits across dynos ([rate limiting](../core/rate-limiting)). Update the Procfile or startup command to pass CLI flags: ``` web: ./authorizer --database-type=$DATABASE_TYPE --database-url=$DATABASE_URL --url=$AUTHORIZER_URL --jwt-type=$JWT_TYPE --jwt-secret=$JWT_SECRET --encryption-key=$ENCRYPTION_KEY --admin-secret=$ADMIN_SECRET --client-id=$CLIENT_ID --client-secret=$CLIENT_SECRET ``` --- ### Updating Instance #### Prerequisites - [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) - [Git](https://git-scm.com/downloads) #### Step 1: Clone Authorizer Heroku App ```bash git clone https://github.com/authorizerdev/authorizer-heroku cd authorizer-heroku ``` #### Step 2: Attach Heroku app ```bash # Replace authorizer-heroku with your Heroku app's name heroku git:remote -a authorizer-heroku heroku stack:set container -a authorizer-heroku ``` #### Step 3: Deploy the latest version ```bash git push heroku main ``` --- ## Deployment Overview ## Deployments These deployment guides show how to run **Authorizer v2** using the **CLI-only configuration model**. Key differences from v1: - No `.env` file loading by the server - No dashboard-based `_update_env` configuration - All config is supplied as **CLI flags** when starting the binary or container ### Required Variables :::info `--encryption-key` (2.4.0+) Encrypts [TOTP](https://datatracker.ietf.org/doc/html/rfc6238) shared secrets and OTP digests at rest. **Required when `--jwt-type` is `RS*`/`ES*`** — with no `--jwt-secret` to fall back to, the server refuses to start without it. With HMAC types (`HS*`) it falls back to `--jwt-secret`, but a distinct value is recommended: rotating the JWT secret otherwise re-keys at-rest data and locks out every enrolled TOTP user. Generate it **once** (`openssl rand -hex 32`), store it as a secret, and keep it stable across restarts — a key that changes on every boot leaves existing TOTP enrolments and pending OTPs undecryptable. Omit the flag on releases before 2.4.0, which do not have it. See [Server Configuration](/core/server-config). ::: All deployments require these flags with sample values: ```bash --database-type=sqlite \ --database-url=test.db \ --url=https://auth.example.com \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` ### Deployment Options | Method | Guide | | ------ | ----- | | Docker | [Docker](./docker) | | Binary / Source | [Binary](./binary) | | Kubernetes | [Kubernetes](./kubernetes) | | Helm Chart | [Helm Chart](./helm-chart) | | Heroku | [Heroku](./heroku) | | Railway | [Railway](./railway) | | Render | [Render](./render) | | Fly.io | [Fly.io](./fly-io) | | Koyeb | [Koyeb](./koyeb) | | EasyPanel | [EasyPanel](./easypanel) | | Alibaba Cloud | [Alibaba Cloud](./alibaba-cloud) | ### Reference - [Getting Started](../getting-started) -- quick start guide - [Server Configuration](../core/server-config) -- all CLI flags - [Migration v1 to v2](../migration/v1-to-v2) -- upgrade guide --- ## Koyeb ## Deploy on Koyeb ### Introduction [Koyeb](https://www.koyeb.com/) is a developer-friendly serverless platform to deploy apps globally with native autoscaling, a global edge network, and built-in service mesh. ### Requirements - A [Koyeb account](https://www.koyeb.com/) - A PostgreSQL database (providers like [Neon](https://neon.tech/) and [Aiven](https://aiven.io/) offer free tiers) ### Deploy an Authorizer Instance [![Deploy to Koyeb](https://www.koyeb.com/static/images/deploy/button.svg)](https://app.koyeb.com/deploy?name=authorizer&type=docker&image=quay.io/authorizer/authorizer&env[PORT]=8000&env[DATABASE_TYPE]=postgres&env[DATABASE_URL]=CHANGE_ME&ports=8000;http;/) #### Step 1: Enter application details Choose the configuration for your deployment: - **Name**: Service name in Koyeb - **Region**: Deployment region - **Instance**: Instance size - **Scaling**: Number of instances ![Koyeb config](/img/koyeb_app_config.png) #### Step 2: Configure the database URL In the **Environment variables** section, set the `DATABASE_URL` to your PostgreSQL connection string. ![Koyeb database URL](/img/koyeb_database_url.png) #### Step 3: Configure v2 required variables Add the following environment variables: | Variable | Example Value | | -------- | ------------- | | `DATABASE_TYPE` | `postgres` | | `DATABASE_URL` | `postgres://user:pass@host:5432/db` | | `JWT_TYPE` | `HS256` | | `JWT_SECRET` | `test` | | `ENCRYPTION_KEY` | *(generate once with `openssl rand -hex 32`)* | | `ADMIN_SECRET` | `admin` | | `CLIENT_ID` | `123456` | | `CLIENT_SECRET` | `secret` | | `AUTHORIZER_URL` | `https://your-app.koyeb.app` *(your public Koyeb URL)* | Update the start command to pass CLI flags: ```bash ./authorizer \ --database-type=$DATABASE_TYPE \ --database-url=$DATABASE_URL \ --url=$AUTHORIZER_URL \ --jwt-type=$JWT_TYPE \ --jwt-secret=$JWT_SECRET \ --encryption-key=$ENCRYPTION_KEY \ --admin-secret=$ADMIN_SECRET \ --client-id=$CLIENT_ID \ --client-secret=$CLIENT_SECRET ``` ![Koyeb authorizer URL](/img/koyeb_authorizer_url.png) --- ## Kubernetes ## Kubernetes (v2) This guide shows how to deploy **Authorizer v2** on Kubernetes using the **CLI-only configuration model**. Instead of configuring env vars that the server reads directly, we pass **CLI flags** through the container `args`. If you are migrating from v1, compare with [Kubernetes](../deployment/kubernetes) and the [Migration v1 to v2](../migration/v1-to-v2) guide. --- ### 1. Prerequisites - A Kubernetes cluster (GKE, EKS, AKS, k3s, etc.). - Container image for **Authorizer v2** built with: ```dockerfile # Official image listens on 8080 (HTTP) and 8081 (metrics); see Dockerfile EXPOSE comments. ENTRYPOINT ["./authorizer"] CMD [] ``` - Optional: - Ingress controller (for example nginx). - cert-manager for automatic TLS. --- ### 2. Deployment manifest (v2-style) Below is an example `Deployment` + `Service` + `Ingress` setup. The key difference vs v1: **we pass configuration as CLI flags in `args`**. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: authorizer-v2 spec: replicas: 1 selector: matchLabels: app: authorizer-v2 template: metadata: labels: app: authorizer-v2 spec: containers: - name: authorizer-v2 image: your-registry/authorizer:v2 imagePullPolicy: Always ports: - containerPort: 8080 name: http - containerPort: 8081 name: metrics env: - name: DATABASE_URL valueFrom: secretKeyRef: name: authorizer-secrets key: database-url - name: CLIENT_ID valueFrom: secretKeyRef: name: authorizer-secrets key: client-id - name: CLIENT_SECRET valueFrom: secretKeyRef: name: authorizer-secrets key: client-secret - name: ADMIN_SECRET valueFrom: secretKeyRef: name: authorizer-secrets key: admin-secret - name: ENCRYPTION_KEY valueFrom: secretKeyRef: name: authorizer-secrets key: encryption-key args: - "--env=production" - "--http-port=8080" - "--metrics-port=8081" - "--metrics-host=0.0.0.0" - "--rate-limit-rps=30" - "--rate-limit-burst=20" - "--rate-limit-fail-closed=false" - "--database-type=postgres" - "--database-url=$(DATABASE_URL)" - "--url=https://YOUR_DOMAIN" - "--client-id=$(CLIENT_ID)" - "--client-secret=$(CLIENT_SECRET)" - "--admin-secret=$(ADMIN_SECRET)" - "--jwt-type=RS256" - "--encryption-key=$(ENCRYPTION_KEY)" # Example: mount keys from files or use env and expand here - "--enable-login-page=true" - "--enable-playground=false" - "--enable-graphql-introspection=false" --- apiVersion: v1 kind: Service metadata: name: authorizer-v2 spec: selector: app: authorizer-v2 ports: - port: 80 name: http targetPort: 8080 type: ClusterIP --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: authorizer-v2 annotations: kubernetes.io/ingress.class: nginx cert-manager.io/cluster-issuer: letsencrypt-prod spec: rules: - host: YOUR_DOMAIN http: paths: - path: / pathType: Prefix backend: service: name: authorizer-v2 port: number: 80 tls: - hosts: - YOUR_DOMAIN secretName: authorizer-v2-tls ``` > **Note:** Use Kubernetes `Secret` resources for sensitive values and reference them via `env` + `args` as shown. #### Ports: `containerPort`, Services, and Ingress {#k8s-ports-services} - Declare **both** `containerPort: 8080` and **`8081`** on the pod so the API contract matches the image (`EXPOSE 8080 8081` in the Dockerfile). This is documentation for humans and tooling; it does not by itself expose traffic to the internet. - The **`Service`** that backs your **Ingress** (or cloud load balancer) should forward **only** the app port (**80 → 8080** in the example above). **Do not** add `8081` to that same public-facing `Service` or `Ingress`. - For [Prometheus](https://prometheus.io), scrape **`8081`** via the **pod network** or a **separate ClusterIP `Service`** (below). Set **`--metrics-host=0.0.0.0`** in `args` so the metrics listener accepts connections from other pods; without it, metrics stay on container loopback and in-cluster scrapes will fail. **Summary:** expose **both** ports on the **Pod**; expose **only HTTP (8080)** to clients via Ingress/LB; keep **metrics (8081)** internal to the cluster. #### Metrics (Prometheus) The app serves **`/metrics` on a second HTTP listener** on port **`8081`**. In Kubernetes, **`--metrics-host=0.0.0.0`** is usually required so Prometheus can scrape the pod IP. **Do not** put port `8081` on an internet-facing `Ingress`. Use a `ServiceMonitor`, PodMonitor, or a dedicated **ClusterIP** `Service` and scrape config only. If Prometheus runs on the **same host** as a bare binary (not K8s), you can keep the default **`127.0.0.1`** for metrics instead. Optional internal `Service` for metrics (ClusterIP only): ```yaml apiVersion: v1 kind: Service metadata: name: authorizer-v2-metrics spec: selector: app: authorizer-v2 ports: - port: 8081 targetPort: metrics name: metrics type: ClusterIP ``` Apply the manifest: ```bash kubectl apply -f authorizer-v2.yaml ``` --- ### 3. Managing configuration changes Because all configuration is now expressed as **CLI flags**: - To change a setting (for example enable playground), update the **`args`** list. - Then run: ```bash kubectl apply -f authorizer-v2.yaml kubectl rollout restart deployment authorizer-v2 ``` You no longer update server config via `_update_env` or dashboard; those are deprecated in v2. For a full list of available flags, see: - [Server Configuration (v2)](../core/server-config) - `./authorizer --help` in the container image --- ## Railway ## Deploy on Railway ### Introduction [Railway](https://railway.app/) is a deployment platform where you can provision infrastructure, develop locally, and deploy to the cloud. ### Requirements A [Railway account](https://railway.app/). ### Deploy an Authorizer Instance Deploy a production-ready Authorizer instance with PostgreSQL and Redis: [![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/deploy/authorizer-1?referralCode=FEF4uT&utm_medium=integration&utm_source=template&utm_campaign=generic) Before getting started, make sure you have given permission to Railway for further deployments as it will create a repository in your GitHub account. ![Railway deployment](/img/railway.png) #### Configure for v2 After deployment, configure the following required variables in Railway's environment settings: | Variable | Example Value | | -------- | ------------- | | `DATABASE_TYPE` | `postgres` | | `DATABASE_URL` | *(auto-configured by Railway)* | | `JWT_TYPE` | `HS256` | | `JWT_SECRET` | `test` | | `ENCRYPTION_KEY` | *(generate once with `openssl rand -hex 32`)* | | `ADMIN_SECRET` | `admin` | | `CLIENT_ID` | `123456` | | `CLIENT_SECRET` | `secret` | | `AUTHORIZER_URL` | `https://your-app.up.railway.app` *(your public Railway URL)* | #### Optional: metrics bind address and rate limits The [authorizer-railway](https://github.com/authorizerdev/authorizer-railway) Dockerfile maps these environment variables to CLI flags (defaults match the Authorizer binary): | Variable | Maps to | Default | When to set | | -------- | ------- | ------- | ----------- | | `METRICS_HOST` | `--metrics-host` | `127.0.0.1` | Use `0.0.0.0` only if something on the same private network must scrape `METRICS_PORT` (never expose metrics on the public internet). | | `METRICS_PORT` | `--metrics-port` | `8081` | Change if the platform collides with this port. | | `RATE_LIMIT_RPS` | `--rate-limit-rps` | `30` | Lower for stricter protection or raise for busy UIs; `0` disables. | | `RATE_LIMIT_BURST` | `--rate-limit-burst` | `20` | Short spike allowance per IP. | | `RATE_LIMIT_FAIL_CLOSED` | `--rate-limit-fail-closed` | `false` | Set `true` to return **503** when the rate-limit backend (e.g. Redis) errors instead of fail-open. | Set `REDIS_URL` when you use multiple instances so sessions and rate limits stay consistent ([rate limiting](../core/rate-limiting)). Update the start command to pass CLI flags: ```bash ./authorizer \ --database-type=$DATABASE_TYPE \ --database-url=$DATABASE_URL \ --url=$AUTHORIZER_URL \ --jwt-type=$JWT_TYPE \ --jwt-secret=$JWT_SECRET \ --encryption-key=$ENCRYPTION_KEY \ --admin-secret=$ADMIN_SECRET \ --client-id=$CLIENT_ID \ --client-secret=$CLIENT_SECRET ``` ### Update Instance Update the [Docker image](https://github.com/authorizerdev/authorizer-railway/blob/main/Dockerfile#L1) to the desired version in the repository created with your deployment. Find all versions on [GitHub](https://github.com/authorizerdev/authorizer/releases) or [Quay](https://quay.io/repository/authorizer/authorizer). --- ## Render ## Deploy on Render ### Introduction [Render](https://render.com/) is a unified cloud to build and run all your apps and websites with free SSL, a global CDN, DDoS protection, private networks, and auto-deploys from Git. ### Requirements A [Render account](https://render.com/). ### Deploy an Authorizer Instance Deploy a production-ready Authorizer instance with a managed PostgreSQL database: [![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/authorizerdev/authorizer-render) > If you already have a PostgreSQL instance, use the [`without-postgres`](https://github.com/authorizerdev/authorizer-render/tree/without-postgres) branch. #### Step 1: Enter app details Enter the name for your instance. ![Render step 1](/img/render_1.png) #### Step 2: Configure for v2 Set the following required environment variables: | Variable | Example Value | | -------- | ------------- | | `DATABASE_TYPE` | `postgres` | | `DATABASE_URL` | *(auto-configured by Render)* | | `JWT_TYPE` | `HS256` | | `JWT_SECRET` | `test` | | `ENCRYPTION_KEY` | *(generate once with `openssl rand -hex 32`)* | | `ADMIN_SECRET` | `admin` | | `CLIENT_ID` | `123456` | | `CLIENT_SECRET` | `secret` | | `AUTHORIZER_URL` | `https://your-app.onrender.com` *(your public Render URL)* | #### Optional: metrics bind address and rate limits The [authorizer-render](https://github.com/authorizerdev/authorizer-render) image expands these variables to CLI flags: | Variable | Maps to | Default | | -------- | ------- | ------- | | `METRICS_HOST` | `--metrics-host` | `127.0.0.1` | | `METRICS_PORT` | `--metrics-port` | `8081` | | `RATE_LIMIT_RPS` | `--rate-limit-rps` | `30` | | `RATE_LIMIT_BURST` | `--rate-limit-burst` | `20` | | `RATE_LIMIT_FAIL_CLOSED` | `--rate-limit-fail-closed` | `false` | See [Metrics & monitoring](../core/metrics-monitoring) and [Rate limiting](../core/rate-limiting). Add `REDIS_URL` if you run more than one instance. Update the start command to pass CLI flags: ```bash ./authorizer \ --database-type=$DATABASE_TYPE \ --database-url=$DATABASE_URL \ --url=$AUTHORIZER_URL \ --jwt-type=$JWT_TYPE \ --jwt-secret=$JWT_SECRET \ --encryption-key=$ENCRYPTION_KEY \ --admin-secret=$ADMIN_SECRET \ --client-id=$CLIENT_ID \ --client-secret=$CLIENT_SECRET ``` ![Render step 2](/img/render_2.png) --- ## Gatsby.js ## Using Authorizer with Gatsby ### Step 1: Get Authorizer Instance Deploy production ready Authorizer instance using one click deployment options available below | **Infra provider** | **One-click link** | **Additional information** | | :----------------: | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------: | | Railway.app | ![Deploy on Railway](https://railway.com/button.svg) | [docs](/deployment/railway) | | Heroku | ![Deploy to Heroku](https://www.herokucdn.com/deploy/button.svg) | [docs](/deployment/heroku) | | Render | ![render button](https://render.com/images/deploy-to-render-button.svg) | [docs](/deployment/render) | For more information check [docs](/getting-started/) ### Step 2: Setup Instance Start your Authorizer instance with the required CLI flags: ```bash ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` Note the `--client-id` value -- you will need it in the SDK configuration below. For more information check [Server Configuration](/core/server-config). ### Step 3: Bootstrap Gatsby Site Run `npm init gatsby` this will call `create-gatsby` and help you bootstrap gatsby site Answer the few bootstrapping questions, - Give your site a name - Select the repo name - Select CMS (For demo purpose I did not select any cms) - Selected `styled-components` for styling system - Select the additional features you want > **Note:** If you use Gatsby 4 (the version used by the [`with-gatsbyjs` example](https://github.com/authorizerdev/examples/tree/main/with-gatsbyjs)), its native dependency `lmdb-store` does not compile on Node.js 20+. Use Node.js 16-18 to run it. ### Step 4: Install `@authorizerdev/authorizer-react` ```sh npm install @authorizerdev/authorizer-react ``` OR ```sh yarn add @authorizerdev/authorizer-react ``` Import the SDK stylesheet once, e.g. in `gatsby-browser.js` (see Step 6): ```js require('@authorizerdev/authorizer-react/styles.css') ``` ### Step 5: Create Root Layout Create `src/components/layout.js` as the root layout for app with `AuthorizerProvider` > Note: Replace `YOUR_AUTHORIZER_URL` with your authorizer instance URL. Replace `YOUR_CLIENT_ID` with the value of `--client-id` flag used to start the server. ```jsx import React from 'react' import { AuthorizerProvider } from '@authorizerdev/authorizer-react' // styles const pageStyles = { color: '#232129', padding: 96, fontFamily: '-apple-system, Roboto, sans-serif, serif', } export default function Layout({ children }) { return (
{children}
) } ``` ### Step 6: Update browser config Add root layout in gatsby browser config. Create `gatsby-browser.js` in the root of project with following content ```jsx require('@authorizerdev/authorizer-react/styles.css') const React = require('react') const Layout = require('./src/components/layout').default // Wraps every page in a component exports.wrapPageElement = ({ element, props }) => { return {element} } ``` This will prevent re-rendering of layout every time the page changes. ### Step 7: Add Authorizer component Add `Authorizer` component in `src/pages/index.js` page with redirects. Here in case if user is logged in we would like to redirect them to private route using `useEffect` Replace content of Index page with following ```jsx import { Authorizer, useAuthorizer } from '@authorizerdev/authorizer-react' import * as React from 'react' import { navigate } from 'gatsby' const IndexPage = () => { const { loading, user } = useAuthorizer() React.useEffect(() => { if (!loading && user) { navigate('/private/dashboard') } }, [loading, user]) if (loading) { return

loading...

} return (
{ navigate('/private/dashboard') }} onLogin={() => { navigate('/private/dashboard') }} />
) } export default IndexPage ``` ### Step 8: Add private route layout Add `src/components/private.js` with following content Here if user is not logged in we would redirect them to home page where we have our Authorizer login component. This also adds logout button which will be common for all private routes ```jsx import * as React from 'react' import { useAuthorizer } from '@authorizerdev/authorizer-react' import { navigate } from 'gatsby' export default function PrivateLayout({ children }) { const { user, loading, authorizerRef, setUser } = useAuthorizer() React.useEffect(() => { if (!loading && !user) { navigate('/') } }, [loading, user]) const handleLogout = async () => { await authorizerRef.logout() setUser(null) navigate('/') } if (loading) { return

loading...

} return (
{children}
) } ``` ### Step 9: Add private route Add `src/pages/private/dashboard.js` with following content ```jsx import * as React from 'react' import { useAuthorizer } from '@authorizerdev/authorizer-react' import PrivateLayout from '../../components/private' export default function Dashboard() { const { user } = useAuthorizer() return ( {JSON.stringify(user, null, 2)} ) } ``` --- ## Hasura ## Using Authorizer with Hasura In this section you will learn how to integrate [Authorizer](https://authorizer.dev) with your Hasura instance and have authorized GraphQL API ready for your application. #### Step 1: Deploy Authorizer Instance To integrate Authorizer with Hasura, you will need an Authorizer instance deployed on your infrastructure or 3rd party cloud services. You can deploy authorizer instance using following one click deployment options: | **Infra provider** | **One-click link** | **Additional information** | | :----------------: | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------: | | Railway.app | ![Deploy on Railway](https://railway.com/button.svg) | [docs](/deployment/railway) | | Heroku | ![Deploy to Heroku](https://www.herokucdn.com/deploy/button.svg) | [docs](/deployment/heroku) | | Render | ![render button](https://render.com/images/deploy-to-render-button.svg) | [docs](/deployment/render) | OR You can also deploy Authorizer instance using - [Docker Image + Kubernetes](/deployment/kubernetes) - [Kubernetes HelmChart](https://github.com/authorizerdev/authorizer-helm-chart) - [Binary](/deployment/binary) - [fly.io](/deployment/fly-io) > **Note:** If you are trying out with one click deployment options like railway then template is configured in a way that it will also deploy postgres + redis for you. For other deployment options, start the server with the required CLI flags: > ```bash > ./authorizer --database-type=sqlite --database-url=test.db --url=http://localhost:8080 --jwt-type=HS256 --jwt-secret=test --encryption-key=test-encryption-key --admin-secret=admin --client-id=123456 --client-secret=secret > ``` > You can also configure `--redis-url` to have persisted sessions. For more information check [Server Configuration](/core/server-config). In case of Hasura, we need to have database type as `postgres` / `mysql` or the one that is supported by Hasura and connect that database with Authorizer instance via Database Environment Variables. #### Step 2: Configure Authorizer instance Configure your Authorizer instance using CLI flags at startup. In v2, all configuration is passed via CLI flags (no dashboard-based env configuration). For example: ```bash ./authorizer \ --database-type=postgres \ --database-url="postgres://user:pass@host:5432/authorizer" \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret \ --google-client-id=YOUR_GOOGLE_CLIENT_ID \ --google-client-secret=YOUR_GOOGLE_CLIENT_SECRET \ --roles=user,admin \ --default-roles=user ``` See [Server Configuration](/core/server-config) for all available flags including social logins, SMTP, roles, and more. #### Step 3: Setup Hasura Instance - Signup on https://cloud.hasura.io/ - Create a project #### Step 4: Configure Database with Hasura Instance - Open the dashboard of Hasura cloud and navigate to your project - Click on `Launch Console` on top right corner - Go to `Data` section and connect to your database Example ![hasura_db_conenction](https://res.cloudinary.com/dcfpom7fo/image/upload/v1661837009/Authorizer/hasura_db_setting_ckdsqu.png) Check the [hasura docs](https://hasura.io/docs/latest/graphql/cloud/getting-started/index/) for more information. > **Note:** If you have used one click deployment option for authorizer you can get database URL from respective platform's env sections. ### Step 5: Configure JWT token with Hasura - Get the JWT type and secret from the `--jwt-type` and `--jwt-secret` (or `--jwt-public-key` for RS256/ES256) flags you used when starting the server - Open the Hasura dashboard and navigate to your project - Open settings and go to `Env vars` section - Add the following env variable to configure the JWT token ``` HASURA_GRAPHQL_JWT_SECRET: {"type": , "key": } ``` Example ![image](https://res.cloudinary.com/dcfpom7fo/image/upload/v1661837310/Authorizer/hasura_jwt_ttuqp2.png) > **Note:** In case of RSA and ECDSA JWT types only provide the public key in PEM encoded string format. Use the values from `--jwt-type` and `--jwt-public-key` flags used when starting the server. Check the [hasura docs](https://hasura.io/docs/latest/graphql/core/auth/authentication/jwt/) for more information. ### Step 6: Configure JWT token Authorization Script In order for Hasura to authorize a user, JWT token needs to have specific keys. You can add those keys by using the `--custom-access-token-script` flag when starting the server. Example: ```js function(user,tokenPayload) { var data = tokenPayload; data['https://hasura.io/jwt/claims'] = { 'x-hasura-user-id': user.id, 'x-hasura-default-role': tokenPayload.allowed_roles[0], 'x-hasura-allowed-roles': user.roles } return data; } ``` ![script-image](https://res.cloudinary.com/dcfpom7fo/image/upload/v1661836293/Authorizer/configure_id_token_yrwb6z.png) Once user login they will get a `id_token` in the response, this token should be used with Hasura queries as `Authorization: Bearer ID_TOKEN`. This will help in making `Authorized` requests. You can configure access control for the various roles that your application needs from Hasura. Configure roles in Authorizer using the `--roles`, `--default-roles`, and `--protected-roles` flags. ![authorizer_roles](https://res.cloudinary.com/dcfpom7fo/image/upload/v1661836262/Authorizer/configure_roles_tfxfyq.png) For more information on access control check [Hasura docs](https://hasura.io/docs/latest/graphql/core/auth/authorization/basics/) You can also stitch Authorizer GraphQl Endpoint with Hasura Remote Schema, that way you can have single endpoint for all your GraphQL queries / mutations. --- ## React Native ## Using Authorizer with React Native Expo In this doc we will see how you can have authentication ready for your mobile application, which is developed using react native and expo. This is the [github repository](https://github.com/authorizerdev/examples/tree/main/with-react-native-expo) having the sample code Here are the 10 steps you need to follow: ### Step 1: Get Authorizer Instance Deploy production ready Authorizer instance using one click deployment options available below | **Infra provider** | **One-click link** | **Additional information** | | :----------------: | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------: | | Railway.app | ![Deploy on Railway](https://railway.com/button.svg) | [docs](/deployment/railway) | | Heroku | ![Deploy to Heroku](https://www.herokucdn.com/deploy/button.svg) | [docs](/deployment/heroku) | | Render | ![render button](https://render.com/images/deploy-to-render-button.svg) | [docs](/deployment/render) | For more information check [docs](/getting-started/) ### Step 2: Setup Instance Start your Authorizer instance with the required CLI flags: ```bash ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` Note the `--client-id` value -- you will need it in the SDK configuration below. Check [Server Configuration](/core/server-config) for all available flags. ### Step 3: Bootstrap react native project The legacy global `expo-cli` (`expo init`) is deprecated. Use `create-expo-app` instead: ``` npx create-expo-app with-react-native-expo --template blank-typescript ``` ### Step 4: Install dependencies ``` npm install @authorizerdev/authorizer-js expo-auth-session expo-crypto expo-secure-store expo-web-browser ``` > Note: `jwt-decode` and `react-native-base64` are **not** needed -- the flow below fetches the user profile via `authorizerRef.getProfile()` instead of decoding a JWT client-side. ### Step 5: Create redirect url Redirect URL is used to redirect back to your application once the authentication process is complete. The `useProxy` option (Expo's auth proxy service) has been removed from `expo-auth-session` -- call `makeRedirectUri()` with no arguments: ```js const redirectUri = AuthSession.makeRedirectUri() ``` ### Step 6: Create AuthorizerJS Client - Get your client ID from the `--client-id` flag used when starting the server ```js const authorizerClientID = 'YOUR_CLIENT_ID' const authorizerURL = 'YOUR_AUTHORIZER_INSTANCE_URL' const authorizationEndpoint = `${authorizerURL}/authorize` const tokenEndpoint = `${authorizerURL}/oauth/token` const authorizerRef = new Authorizer({ clientID: authorizerClientID, authorizerURL: authorizerURL, redirectURL: redirectUri, }) ``` ### Step 7: Setup Expo AuthSession Configure `useAuthRequest` hook with above configs. The example uses the **authorization code + PKCE** flow (`responseType: 'code'`, `usePKCE: true`) rather than the implicit `token` flow, since Expo's `expo-auth-session` treats PKCE as the secure default for public clients. > Note: Use `offline_access` in scope if you want to get refresh token and want to perform silent refresh when user comes back to app. If your app is data sensitive we do not recommend using refresh token (example banking / finance app) ```js const [request, result, promptAsync] = AuthSession.useAuthRequest( { redirectUri, clientId: authorizerClientID, responseType: 'code', // use offline access to get a refresh token and perform silent refresh in background scopes: ['openid', 'profile', 'email', 'offline_access'], extraParams: { // ideally, this will be a random value nonce: 'nonce', }, usePKCE: true, }, { authorizationEndpoint } ) ``` ### Step 8: Handle the authentication result On success, exchange the authorization code for tokens with `AuthSession.exchangeCodeAsync()`, store the refresh token, then fetch the profile with the access token to get the user's email. ```js const authorizerRefreshTokenKey = `authorizer_refresh_token` useEffect(() => { async function setResult() { if (result && result.type === 'success') { if (result.error) { Alert.alert( 'Authentication error', result.params.error_description || 'something went wrong' ) return } const codeRes = await AuthSession.exchangeCodeAsync( { code: result.params.code, redirectUri, clientId: authorizerClientID, extraParams: { code_verifier: request?.codeVerifier || '', }, }, { tokenEndpoint } ) if (codeRes?.refreshToken) { await SecureStore.setItemAsync( authorizerRefreshTokenKey, codeRes.refreshToken ) } // get profile using the access token const { data: profileData } = await authorizerRef.getProfile({ Authorization: `Bearer ${codeRes?.accessToken}`, }) setEmail(profileData?.email ?? undefined) } } setResult() }, [result]) ``` ### Step 9: Silent Refresh Perform Silent Refresh. Note silent refresh will give you a new access token and refresh token, which you can then use to re-fetch the profile. ```js // on init of app silently refresh token if it exists useEffect(() => { async function silentRefresh() { try { const refreshToken = await SecureStore.getItemAsync( authorizerRefreshTokenKey ) if (refreshToken) { try { const { data } = await authorizerRef.getToken({ grant_type: 'refresh_token', refresh_token: refreshToken, }) await SecureStore.setItemAsync( authorizerRefreshTokenKey, data?.refresh_token || '' ) // get profile using the new access token const { data: profileData } = await authorizerRef.getProfile({ Authorization: `Bearer ${data?.access_token}`, }) setEmail(profileData?.email ?? undefined) } catch (err) { console.error(err) await SecureStore.deleteItemAsync(authorizerRefreshTokenKey) } } } catch (error) { setEmail(undefined) await SecureStore.deleteItemAsync(authorizerRefreshTokenKey) } finally { setLoading(false) } } silentRefresh() }, []) ``` Also you can perform silent refresh when the access token expires. You also get `expires_in` in the response of token which you can use. So you can set time interval after which it should fetch new tokens. ### Step 10: Logout Revoke the refresh token, clear it from `SecureStore`, and open the Authorizer `/logout` endpoint in a browser session so the server-side cookie is cleared too: ```js const handleLogout = async () => { setLoading(true) setEmail(undefined) try { const refreshToken = await SecureStore.getItemAsync( authorizerRefreshTokenKey ) await authorizerRef.revokeToken({ refresh_token: refreshToken || '', }) await SecureStore.deleteItemAsync(authorizerRefreshTokenKey) await WebBrowser.openAuthSessionAsync( `${authorizerURL}/logout?redirect_uri=${redirectUri}`, 'redirectUrl' ) } catch (err) { console.log(err) } finally { setLoading(false) } } ``` --- ## SurrealDB ## Using Authorizer with SurrealDB [SurrealDB](https://surrealdb.com) can verify tokens issued by an external identity provider and use their claims in table permissions. This guide sets up Authorizer as that provider, so a client-side application can use SurrealDB as its only backend: users sign in with Authorizer, and SurrealDB only lets each user read and write their own records. :::info Requires Authorizer v2.4.8 or later SurrealDB selects the verification key by the token's `kid` header. Authorizer adds a `kid` to every RS256/ES256 token from v2.4.8. With an earlier version SurrealDB refuses every token with `401`; its debug log (`--log debug`) shows `Missing token header 'kid'`. ::: ### Using SurrealDB as Authorizer's database too Authorizer can also keep its own data — users, sessions, clients, organizations — in SurrealDB with `--database-type=surrealdb` (see [Databases](../core/databases)). Point both at the same SurrealDB and your identities, auth data and application data live in one database, backed up together. Authorizer's tables use the `authorizer_` prefix, so they sit alongside yours. ### How it works 1. The user signs in with Authorizer and receives an access token. 2. The application sends the token to SurrealDB, with the SDK's `authenticate()` or an `Authorization: Bearer` header. 3. SurrealDB finds the access method named by the token's `ns`, `db` and `ac` claims, and verifies the signature against Authorizer's JWKS at `/.well-known/jwks.json`. 4. The access method's `AUTHENTICATE` block checks the issuer, audience and verified email, and returns the user's record. 5. Table `PERMISSIONS` apply to every query in that session. ### Step 1: Configure Authorizer Authorizer must sign tokens with an asymmetric key: `--jwt-type=RS256` (or `ES256`) with `--jwt-private-key` and `--jwt-public-key`. HMAC keys (`HS256`) are never published in the JWKS, so SurrealDB cannot verify tokens signed with them. SurrealDB needs the namespace, database and access method in the token. Add them with a [custom access token script](../core/server-config): ```bash --custom-access-token-script='function(user, tokenPayload) { return { ns: "main", // namespace used in DEFINE ACCESS db: "main", // database used in DEFINE ACCESS ac: "authorizer", // name of the access method email: user.email, email_verified: user.email_verified }; }' ``` Every access token already carries `iss` (your `--url`), `aud` and `client_id` (your `--client-id`), `sub` (the user ID), `exp` and `roles`. Add your application's origin to `--allowed-origins` (for example `--allowed-origins=https://app.example.com`). With the default, `*`, Authorizer accepts sign-in requests only from its own origin and refuses the rest with `403 Origin not allowed`. ### Step 2: Configure SurrealDB Start SurrealDB with network access to Authorizer, so it can download the JWKS: ```bash surreal start --user root --pass secret --allow-net auth.example.com ``` :::caution Private networks SurrealDB also checks the IP address the host resolves to. If Authorizer runs on a private network (for example as another container), allow that address too: `--allow-net auth.internal,10.0.0.12`. If the JWKS cannot be downloaded, every token is refused with 401, and SurrealDB logs the reason, for example `Access to network target '10.0.0.12/32' is not allowed`. ::: Then define a table and the access method: ```sql USE NS main DB main; -- Each user can only see and change their own record. DEFINE TABLE user SCHEMAFULL PERMISSIONS FOR select, update, delete, create WHERE $access = "authorizer" AND id = $auth; DEFINE FIELD email ON user TYPE string ASSERT string::is_email($value); DEFINE INDEX email ON user FIELDS email UNIQUE; DEFINE FIELD nickname ON user TYPE option; DEFINE ACCESS authorizer ON DATABASE TYPE RECORD WITH JWT URL "https://auth.example.com/.well-known/jwks.json" AUTHENTICATE { IF ( $token.iss = "https://auth.example.com" AND $token.aud = "" AND $token.email_verified = true ) { -- The record is keyed by the Authorizer user ID, which never changes. LET $user = type::record("user", $token.sub); -- Create it the first time this user authenticates. IF !record::exists($user) { CREATE $user SET email = $token.email; }; RETURN $user; } }; ``` Replace `https://auth.example.com` with your Authorizer URL and `` with your client ID. #### Role-based permissions The `roles` claim can be used directly in permissions. Here every signed-in user can read posts, but only users with the `admin` role can write them: ```sql DEFINE TABLE post SCHEMAFULL PERMISSIONS FOR select WHERE $access = "authorizer" FOR create, update, delete WHERE $access = "authorizer" AND $token.roles CONTAINS "admin"; DEFINE FIELD title ON post TYPE string; ``` ### Step 3: Sign in and query ```ts import { Authorizer } from '@authorizerdev/authorizer-js'; import { Surreal } from 'surrealdb'; const authorizer = new Authorizer({ authorizerURL: 'https://auth.example.com', redirectURL: window.location.origin, clientID: '', }); const { data, errors } = await authorizer.login({ email, password }); if (errors.length) throw errors[0]; const db = new Surreal(); await db.connect('wss://your-surrealdb.example.com'); await db.authenticate(data.access_token); // One result per statement. The first holds only the signed-in user's own record. const [users] = await db.query('SELECT * FROM user'); ``` `login()` returns a token only once sign-in is complete. If the user has set up multi-factor authentication, or Authorizer is offering to set it up, the response asks for that step first; the [hosted login page](../core/oauth2-oidc) handles it for you. Or over HTTP: ```bash curl -X POST https://your-surrealdb.example.com/sql \ -H "Accept: application/json" \ -H "Authorization: Bearer $ACCESS_TOKEN" \ --data-binary 'SELECT * FROM user;' ``` ### Notes - **Sign-out and revocation:** SurrealDB verifies tokens on its own and does not ask Authorizer whether a session is still active. Signing out stops new tokens being issued, but a token already in use stays valid until it expires. Access tokens last 30 minutes; refresh them with the SDK. - **Key rotation:** SurrealDB caches the JWKS for up to 12 hours and downloads it again for an unknown `kid` at most once every 5 minutes. During a [manual key rotation](../core/oauth2-oidc#manual-key-rotation) this means: - after Authorizer starts signing with the new key, SurrealDB can refuse tokens signed with it for up to 5 minutes; - a key you remove from Authorizer stays trusted by SurrealDB until its cache is replaced, up to 12 hours. Its tokens still expire after 30 minutes, so this matters only for a compromised key: restart SurrealDB to empty the cache. Both periods are set with SurrealDB's `SURREAL_JWKS_CACHE_COOLDOWN_SECONDS` and `SURREAL_JWKS_CACHE_EXPIRATION_SECONDS`. Each key's `kid` is its thumbprint and does not change when it becomes the secondary key, so tokens signed before the swap keep working. - **Security checks:** SurrealDB rejects tokens with a tampered signature or claims, `alg: none`, and HMAC tokens forged against the published key. --- ## Migration v1 to v2 ## Migration Guide: Authorizer v1 to v2 This page helps you migrate from **Authorizer v1** to **Authorizer v2**. The v2 server focuses on **CLI-based configuration**, **better secret handling**, and **deployment hardening**. --- ### 1. Major Security and Configuration Change #### What changed In **v1**, environment and configuration could be: - Loaded from `.env` or OS environment variables. - Stored and updated in **cache (e.g. Redis)** or **database** via the dashboard or `_update_env` mutation. In **v2**: - **All configuration is passed at server start via CLI root arguments.** - Nothing is read from a persisted "env store" in cache or DB. - Secrets and config are not stored in your database or cache. They are supplied explicitly at startup (for example via your orchestrator, platform env to CLI args, or a wrapper script). #### What you need to do 1. **Copy all your existing v1 credentials and environment configuration BEFORE migrating.** :::danger Critical — do not skip this step You must capture all your v1 env variables before migrating. Missing values will cause the v2 server to fail or behave incorrectly, and **you will not be able to recover them after shutting down v1**. ::: **How to get your current env variables:** - **Option 1: Using the `_env` query (recommended)** Query the `_env` GraphQL field with your admin secret to export all current configuration: ```bash curl --location 'YOUR_AUTHORIZER_URL/graphql' \ --header 'x-authorizer-admin-secret: YOUR_ADMIN_SECRET' \ --header 'Content-Type: application/json' \ --data '{ "query": "{\n _env {\n CLIENT_ID\n CLIENT_SECRET\n GOOGLE_CLIENT_ID\n GOOGLE_CLIENT_SECRET\n GITHUB_CLIENT_ID\n GITHUB_CLIENT_SECRET\n FACEBOOK_CLIENT_ID\n FACEBOOK_CLIENT_SECRET\n LINKEDIN_CLIENT_ID\n LINKEDIN_CLIENT_SECRET\n APPLE_CLIENT_ID\n APPLE_CLIENT_SECRET\n DISCORD_CLIENT_ID\n DISCORD_CLIENT_SECRET\n TWITTER_CLIENT_ID\n TWITTER_CLIENT_SECRET\n MICROSOFT_CLIENT_ID\n MICROSOFT_CLIENT_SECRET\n MICROSOFT_ACTIVE_DIRECTORY_TENANT_ID\n TWITCH_CLIENT_ID\n TWITCH_CLIENT_SECRET\n ROBLOX_CLIENT_ID\n ROBLOX_CLIENT_SECRET\n DEFAULT_ROLES\n PROTECTED_ROLES\n ROLES\n JWT_TYPE\n JWT_SECRET\n JWT_ROLE_CLAIM\n JWT_PRIVATE_KEY\n JWT_PUBLIC_KEY\n REDIS_URL\n SMTP_HOST\n SMTP_PORT\n SMTP_USERNAME\n SMTP_PASSWORD\n SMTP_LOCAL_NAME\n SENDER_EMAIL\n SENDER_NAME\n ALLOWED_ORIGINS\n ORGANIZATION_NAME\n ORGANIZATION_LOGO\n ADMIN_SECRET\n APP_COOKIE_SECURE\n ADMIN_COOKIE_SECURE\n DISABLE_LOGIN_PAGE\n DISABLE_MAGIC_LINK_LOGIN\n DISABLE_EMAIL_VERIFICATION\n DISABLE_BASIC_AUTHENTICATION\n DISABLE_MOBILE_BASIC_AUTHENTICATION\n DISABLE_SIGN_UP\n DISABLE_STRONG_PASSWORD\n DISABLE_REDIS_FOR_ENV\n CUSTOM_ACCESS_TOKEN_SCRIPT\n DATABASE_NAME\n DATABASE_TYPE\n DATABASE_URL\n ACCESS_TOKEN_EXPIRY_TIME\n DISABLE_MULTI_FACTOR_AUTHENTICATION\n ENFORCE_MULTI_FACTOR_AUTHENTICATION\n DEFAULT_AUTHORIZE_RESPONSE_TYPE\n DEFAULT_AUTHORIZE_RESPONSE_MODE\n DISABLE_PLAYGROUND\n DISABLE_TOTP_LOGIN\n DISABLE_MAIL_OTP_LOGIN\n __typename\n }\n}", "variables": {} }' ``` - **Option 2: Copy from the v1 dashboard** Go through your v1 dashboard settings and copy every value you configured. This includes: - **OAuth / app:** `client_id`, `client_secret`, `admin_secret` - **Social / OAuth providers:** Google, GitHub, Facebook, Microsoft, Apple, LinkedIn, Discord, Twitter, Twitch, Roblox client IDs and secrets - **Roles:** `roles`, `default_roles`, `protected_roles` - **JWT:** `jwt_type`, `jwt_secret` (or `jwt_private_key` / `jwt_public_key`) - **Session / memory store:** `redis_url` (if using Redis) - **Email / SMTP:** `smtp_host`, `smtp_port`, `smtp_username`, `smtp_password`, `smtp_sender_email`, `smtp_sender_name` - **Domain / origins:** `allowed_origins` - **Access token custom scripts:** `custom_access_token_script` You will need to pass each of these as a CLI flag in v2 for a smooth transition. 2. **Stop relying on dashboard or `_update_env` for server configuration.** In v2, the server does not load or save config from/to DB or cache. Configure everything when starting the server. 3. **Map your current v1 env vars to v2 CLI flags.** Use the configuration mapping below and pass options when starting the binary (see [Running the server](#2-running-the-server)). 4. **Ensure required flags are set at startup.** The v2 server will fail to start if critical flags are missing. At minimum you must provide: - `--database-type` and `--database-url` (or individual `--database-host`, `--database-port`, `--database-name`, `--database-username`, `--database-password`) — the server cannot start without a database connection. - `--url` — this server's own canonical base URL (e.g. `https://auth.example.com`). **Required as of 2.4.0**; the server exits if it is missing or malformed. Not the same as `--allowed-origins` — see [Trusted base URL](../core/security#trusted-base-url). - `--client-id` and `--client-secret` — **required**; the server will exit if they are missing. - `--admin-secret` — needed for admin dashboard access and admin API operations. - `--jwt-type` and `--jwt-secret` (for HMAC algorithms like HS256) or `--jwt-private-key` / `--jwt-public-key` (for RSA/ECDSA algorithms) — needed for token signing and verification. - `--encryption-key` — encrypts [TOTP](https://datatracker.ietf.org/doc/html/rfc6238) secrets and OTP digests at rest (2.4.0+). **Required for RSA/ECDSA deployments**, which have no `--jwt-secret` to fall back to; the server refuses to start without it. HMAC deployments fall back to `--jwt-secret` automatically. --- ### 2. Running the Server #### v1 (typical) ```bash # .env or OS env export DATABASE_TYPE=sqlite export DATABASE_URL=data.db export CLIENT_ID=... export CLIENT_SECRET=... ./authorizer ``` Or configure via dashboard after first run. #### v2 (recommended) Pass all config as **CLI arguments** when starting the server: ```bash ./authorizer \ --database-type=sqlite \ --database-url=data.db \ --url=http://localhost:8080 \ --client-id=YOUR_CLIENT_ID \ --client-secret=YOUR_CLIENT_SECRET \ --admin-secret=your-admin-secret \ --jwt-type=HS256 \ --jwt-secret=your-jwt-secret \ --encryption-key=your-encryption-key ``` For local development (from repo root): ```bash make dev # or go run main.go --database-type=sqlite --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 --jwt-secret=test --encryption-key=test-encryption-key --admin-secret=admin \ --client-id=123456 --client-secret=secret ``` #### Using environment variables with v2 The v2 server does **not** read from `.env` or from a fixed set of OS env vars. To keep using env vars in your deployment: - **Option A:** Set env vars in your platform (Docker, K8s, Railway, etc.) and pass them into the process as arguments via a wrapper script or `envsubst`: ```bash ./authorizer \ --database-type="$DATABASE_TYPE" \ --database-url="$DATABASE_URL" \ --url="$AUTHORIZER_URL" \ --client-id="$CLIENT_ID" \ --client-secret="$CLIENT_SECRET" \ --encryption-key="$ENCRYPTION_KEY" \ ... ``` - **Option B:** Use your platform's way of injecting env into the command line (for example Docker `CMD` or Kubernetes command/args that reference env). Example Docker run: ```bash docker run -p 8080:8080 \ -e DATABASE_TYPE=postgres \ -e DATABASE_URL="postgres://..." \ -e CLIENT_ID=... \ -e CLIENT_SECRET=... \ -e ENCRYPTION_KEY=your-encryption-key \ your-authorizer-image \ ./authorizer \ --database-type="$DATABASE_TYPE" \ --database-url="$DATABASE_URL" \ --url="$AUTHORIZER_URL" \ --client-id="$CLIENT_ID" \ --client-secret="$CLIENT_SECRET" \ --admin-secret="$ADMIN_SECRET" \ --encryption-key="$ENCRYPTION_KEY" ``` #### Build from source (v2) ##### Prerequisites - Go >= 1.24 (see `go.mod` in the main repo). - Node.js >= 18 and npm / pnpm / yarn (only required if you want to build the web UIs). ##### Steps 1. **Clone the repo** ```bash git clone https://github.com/authorizerdev/authorizer.git cd authorizer ``` 2. **Build the server binary** ```bash go build -o build/authorizer . ``` 3. **(Optional) Build the web app and dashboard** ```bash cd web/app && npm ci && npm run build cd ../dashboard && npm ci && npm run build cd ../.. # back to repo root ``` 4. **Run the server with CLI args** ```bash ./build/authorizer \ --database-type=sqlite \ --database-url=data.db \ --url=http://localhost:8080 \ --client-id=YOUR_CLIENT_ID \ --client-secret=YOUR_CLIENT_SECRET \ --admin-secret=your-admin-secret \ --jwt-type=HS256 \ --jwt-secret=your-jwt-secret ``` --- ### 3. Configuration Mapping (v1 env / v1 behavior to v2 CLI flags) Use these v2 **CLI flags** instead of v1 env or dashboard config. Flag names use **kebab-case** (for example `--database-url`). #### Deprecated v1-style flag names (do not use) - `database_url` -- use `--database-url` - `database_type` -- use `--database-type` - `env_file` -- **no longer supported** - `log_level` -- use `--log-level` - `redis_url` -- use `--redis-url` #### Core / server | v1 (env or behavior) | v2 CLI flag | | -------------------- | ----------- | | `ENV` | `--env` | | `PORT` | `--http-port` (default: 8080) | | Host | `--host` (default: 0.0.0.0) | | Metrics port | `--metrics-port` (default: 8081) | | Metrics bind | `--metrics-host` (default: `127.0.0.1`) for the dedicated metrics listener | | `LOG_LEVEL` | `--log-level` | **`GET /metrics` is always** on the dedicated metrics listener at **`--metrics-host`:`--metrics-port`** (default **loopback**); **`--http-port` and `--metrics-port` must differ**. Health probes remain on the HTTP port. For in-cluster [Prometheus](https://prometheus.io), set **`--metrics-host=0.0.0.0`** and scrape over the private network. #### Database | v1 | v2 CLI flag | | ----------------- | ----------- | | `DATABASE_TYPE` | `--database-type` | | `DATABASE_URL` | `--database-url` | | `DATABASE_NAME` | `--database-name` | | `DATABASE_USERNAME` | `--database-username` | | `DATABASE_PASSWORD` | `--database-password` | | `DATABASE_HOST` | `--database-host` | | `DATABASE_PORT` | `--database-port` | | `DATABASE_CERT`, `DATABASE_CA_CERT`, `DATABASE_CERT_KEY` | `--database-cert`, `--database-ca-cert`, `--database-cert-key` | | Couchbase | `--couchbase-bucket`, `--couchbase-scope`, `--couchbase-ram-quota` | | AWS/DynamoDB | `--aws-region`, `--aws-access-key-id`, `--aws-secret-access-key` | #### Memory store (sessions) | v1 | v2 CLI flag | | ----------- | ----------- | | `REDIS_URL` | `--redis-url` | #### OAuth / app | v1 | v2 CLI flag | | ------------------ | ----------- | | `CLIENT_ID` | `--client-id` **(required)** | | `CLIENT_SECRET` | `--client-secret` **(required)** | | `ADMIN_SECRET` | `--admin-secret` | | `ALLOWED_ORIGINS` | `--allowed-origins` (slice; default `*`) | | `DEFAULT_AUTHORIZE_RESPONSE_TYPE` / `MODE` | `--default-authorize-response-type`, `--default-authorize-response-mode` | #### Organization / UI | v1 | v2 CLI flag | | -------------------- | ----------- | | `ORGANIZATION_NAME` | `--organization-name` | | `ORGANIZATION_LOGO` | `--organization-logo` | | `DISABLE_LOGIN_PAGE` | `--enable-login-page` (inverted: use `false` to disable) | | `DISABLE_PLAYGROUND` | `--enable-playground` (inverted: use `false` to disable) | | N/A (GraphQL introspection always on) | `--enable-graphql-introspection` (default `true`; set `false` to disable schema introspection in hardened environments) | #### Auth behavior | v1 | v2 CLI flag | | --------------------------------| ----------- | | Roles | `--roles`, `--default-roles`, `--protected-roles` | | `DISABLE_STRONG_PASSWORD` | `--enable-strong-password` (inverted) | | `DISABLE_BASIC_AUTHENTICATION` | `--enable-basic-authentication` (inverted) | | `DISABLE_EMAIL_VERIFICATION` | `--enable-email-verification` (inverted) | | `DISABLE_MAGIC_LINK_LOGIN` | `--enable-magic-link-login` (inverted) | | `ENFORCE_MULTI_FACTOR_AUTHENTICATION` | `--enforce-mfa` (default flipped: `true` → `false`; MFA is now optional unless you set this) | | `DISABLE_SIGN_UP` | `--enable-signup` (inverted) | | TOTP / OTP / [WebAuthn](https://www.w3.org/TR/webauthn-2/) | **Breaking**: `--enable-mfa`, `--enable-totp-login`, `--enable-email-otp`, and `--enable-sms-otp` are removed. TOTP, email OTP, SMS OTP, and WebAuthn-as-MFA are now **on by default**; opt out with `--disable-totp-login`, `--disable-email-otp`, `--disable-sms-otp`, `--disable-webauthn-mfa`, or turn everything off at once with `--disable-mfa`. See [MFA & WebAuthn/passkeys flags](../core/server-config#multi-factor-authentication-mfa--webauthnpasskeys). | | Mobile basic auth | `--enable-mobile-basic-authentication` | | Phone verification | `--enable-phone-verification` | #### Cookies | v1 | v2 CLI flag | | ----------------------------------------- | ----------- | | `APP_COOKIE_SECURE`, `ADMIN_COOKIE_SECURE` | `--app-cookie-secure`, `--admin-cookie-secure` | | _(new in v2)_ | `--app-cookie-same-site` (values: `none`, `lax`, `strict`; default: `none`) | #### JWT | v1 | v2 CLI flag | | -------------------------- | ----------- | | `JWT_TYPE` | `--jwt-type` | | `JWT_SECRET` | `--jwt-secret` | | `JWT_PRIVATE_KEY`, `JWT_PUBLIC_KEY` | `--jwt-private-key`, `--jwt-public-key` | | `JWT_ROLE_CLAIM` | `--jwt-role-claim` | | *(new in 2.4.0)* | `--encryption-key` | | `CUSTOM_ACCESS_TOKEN_SCRIPT` | `--custom-access-token-script` | #### SMTP | v1 | v2 CLI flag | | ------------------------- | ----------- | | `SMTP_HOST`, `SMTP_PORT` | `--smtp-host`, `--smtp-port` | | `SMTP_USERNAME`, `SMTP_PASSWORD` | `--smtp-username`, `--smtp-password` | | `SENDER_EMAIL`, `SENDER_NAME` | `--smtp-sender-email`, `--smtp-sender-name` | | `SMTP_LOCAL_NAME` | `--smtp-local-name` | | Skip TLS verify | `--smtp-skip-tls-verification` | #### Twilio (SMS) | v1 | v2 CLI flag | | ------------------------------------------------------ | ----------- | | `TWILIO_ACCOUNT_SID`, `TWILIO_API_KEY`, `TWILIO_API_SECRET`, `TWILIO_SENDER` | `--twilio-account-sid`, `--twilio-api-key`, `--twilio-api-secret`, `--twilio-sender` | #### Social / OAuth providers Each provider is configured with `---client-id`, `---client-secret`, and optionally `---scopes`, for example: - `--google-client-id`, `--google-client-secret`, `--google-scopes` - `--github-client-id`, `--github-client-secret`, `--github-scopes` - `--facebook-client-id`, `--facebook-client-secret`, `--facebook-scopes` - `--microsoft-client-id`, `--microsoft-client-secret`, `--microsoft-tenant-id`, `--microsoft-scopes` - `--apple-client-id`, `--apple-client-secret`, `--apple-scopes` - `--linkedin-client-id`, `--linkedin-client-secret`, `--linkedin-scopes` - `--discord-client-id`, `--discord-client-secret`, `--discord-scopes` - `--twitter-client-id`, `--twitter-client-secret`, `--twitter-scopes` - `--twitch-client-id`, `--twitch-client-secret`, `--twitch-scopes` - `--roblox-client-id`, `--roblox-client-secret`, `--roblox-scopes` #### Other | v1 | v2 CLI flag | | ------------------- | ----------- | | `RESET_PASSWORD_URL` | `--reset-password-url` | #### Admin / GraphQL security flags (v2-only) The following flags are **new in v2** and help harden your deployment: - **`--disable-admin-header-auth`**: when set to `true`, the server **does not** accept `X-Authorizer-Admin-Secret` as admin authentication; only the secure admin cookie is honored. - **Recommended for production**: `--disable-admin-header-auth=true`. - **`--enable-graphql-introspection`**: controls whether GraphQL introspection is enabled on `/graphql`. - Default is `true` (for development and tooling). - For locked-down production, you can set `--enable-graphql-introspection=false` to prevent unauthenticated schema discovery. To see all flags and defaults: ```bash ./authorizer --help ``` #### Upgrading from 2.3.x to 2.4.0 Two flags became **mandatory** in 2.4.0. Unlike the changes below, these do not cause silent regressions — the server refuses to start, so you find out immediately. Set both before restarting. ##### `--url` is now required Every deployment must declare its own canonical address: ```bash ./authorizer --url=https://auth.example.com ... ``` Previously optional; leaving it empty made the server derive its own host from request headers, which is a host-header-injection account-takeover surface (CWE-640) — a forged `Host` causes a genuine password-reset link to be emailed pointing at an attacker-controlled domain. See [Trusted base URL](../core/security#trusted-base-url) for the full rationale and for how `--url` differs from `--allowed-origins`. A malformed value is rejected too, not just an empty one: `--url` must be an absolute `http(s)` URL with a host and no user info. `auth.example.com` (no scheme) fails startup rather than being silently ignored. **If you serve several hostnames from one instance:** that only ever worked on the vulnerable header-derived path. Pick the canonical one. Verified organization domains are unaffected — they route email domains to organizations for home realm discovery and have nothing to do with HTTP virtual hosting. ##### `--encryption-key` is required for RS*/ES* deployments A deployment using `--jwt-private-key`/`--jwt-public-key` without `--jwt-secret` refuses to start until `--encryption-key` is set. HMAC deployments (HS256/384/512) still resolve the key from the JWT secret and are unaffected, though setting a distinct key is strongly recommended. If you ran **2.2.1 through 2.4.0-rc.13** with asymmetric JWTs and no `--jwt-secret`, treat existing TOTP enrollments as compromised — they were encrypted under a public constant compiled into the source. Rotate the key and have affected users re-enroll; ciphertext written under the old key will not decrypt. Recovery codes are unaffected (unkeyed SHA-256 digests). ##### Delegated agent checks now fail closed If you use [agent identity](../enterprise/agent-identity) and your authorization model does not declare `type agent`, delegated permission checks are now **denied** instead of authorizing as the delegating user alone. Add `type agent` to the model, or set `--fga-allow-unconstrained-agents` while you migrate. Deployments not using delegation are unaffected. #### Breaking changes — April 2026 security batch If you are upgrading **across** the April 2026 security release (any release on or after that date), two existing flags now have stricter behaviour. Both will cause silent regressions if you don't address them during the upgrade: ##### `--admin-secret` is now required In earlier v2 releases, `--admin-secret` defaulted to the literal string `password` if you forgot to set it. That default is gone. The server now exits at startup with a fatal error when the flag is empty or missing: ``` FATAL: --admin-secret is required and must not be empty. ``` **Action required:** set `--admin-secret` to any non-empty value before restarting. The strength of the secret is your responsibility — the server only enforces non-emptiness. ```bash ./authorizer --admin-secret="$(openssl rand -hex 32)" ... ``` ##### `--trusted-proxies` defaults to none Per-IP rate limiting, audit logs, Prometheus metrics, and CSRF same-origin checks now read the client IP from `RemoteAddr` by default and **ignore** `X-Forwarded-For`. This closes a spoofing hole where any client could pretend to be a different IP by sending a forged `X-Forwarded-For` header. If your Authorizer instance is **directly exposed to the internet** (no proxy in front), you don't need to do anything — the new default is correct. If your Authorizer instance is **behind a reverse proxy** (nginx, AWS ALB, Cloudflare, an ingress controller, etc.), you must opt in by listing the proxy network in CIDR form. Otherwise, every request will appear to come from the proxy IP and per-IP rate limiting will trip on its first burst: ```bash # Behind nginx on the same host ./authorizer --trusted-proxies=127.0.0.1/32,::1/128 ... # Inside a Kubernetes cluster ./authorizer --trusted-proxies=10.0.0.0/8 ... # Behind Cloudflare ./authorizer --trusted-proxies=$(cat cloudflare-ips.txt | paste -sd, -) ... ``` See the new [Security Hardening](../core/security#trusted-proxies) page for the full topology table and flag reference. #### Database schema: `email` / `phone_number` are no longer `UNIQUE` In v1 the `email` and `phone_number` columns of the `authorizer_users` and `authorizer_otps` tables had **database-level `UNIQUE` constraints**. In v2 they are plain (non-unique) indexes, and uniqueness is enforced in the **application layer** instead (the create/update paths reject a duplicate email or phone number with `user with given email already exists`). **Why the change:** - **Uniform behaviour across all 13+ databases.** A SQL `UNIQUE` constraint only exists on the relational backends and treats `NULL`s differently per engine. Enforcing in code gives identical semantics on Postgres, MySQL, MongoDB, DynamoDB, Cassandra, etc. - **`email` and `phone_number` are now optional.** v2 supports email-only and phone-only signups, so a user row may legitimately have a `NULL` email or phone number — a hard `UNIQUE` constraint on a nullable column is awkward and inconsistent. ##### Symptom on upgrade When v2 runs its automatic schema migration against a database created by v1, GORM detects the columns are still unique and tries to drop the old constraint — but under its own generated name (`uni__`), which does **not** match the name Postgres/MySQL actually assigned (`
__key`). The migration then aborts at startup: ``` ERROR: constraint "uni_authorizer_users_email" of relation "authorizer_users" does not exist (SQLSTATE 42704) ALTER TABLE "authorizer_users" DROP CONSTRAINT "uni_authorizer_users_email" failed to create storage provider ``` You may see the same error for `authorizer_otps`, and for the `phone_number` column of either table (`uni_authorizer_users_phone_number`, `uni_authorizer_otps_email`, `uni_authorizer_otps_phone_number`). Depending on which v1 release created your database, the old uniqueness can take any of these forms: - a **UNIQUE constraint** under almost any name — `authorizer_users_email_key` (the Postgres default), `idx_authorizer_otps_phone_number` (a v1 `gorm:"uniqueIndex"` that the database promoted to a constraint), or a custom name from a hand-rolled migration; **or** - a standalone **UNIQUE index** created with `CREATE UNIQUE INDEX`. :::warning A constraint's backing index **cannot** be removed with `DROP INDEX` — Postgres rejects it with `cannot drop index ... because constraint ... requires it`. Use `DROP CONSTRAINT` for those (the index disappears with the constraint). ::: ##### Fix Authorizer **drops these stale unique objects automatically** at startup — by their *real* names, whatever they are — before running the migration. On a current build no action is required; just upgrade to the latest server. If you are pinned to an older build that still fails with the error above, clear them manually once, then restart. **1. List the real names** of the single-column unique objects on these columns: ```sql -- Postgres / Yugabyte / CockroachDB -- (a) UNIQUE constraints — drop each with ALTER TABLE ... DROP CONSTRAINT SELECT conrelid::regclass AS "table", conname AS name FROM pg_constraint WHERE conrelid IN ('authorizer_users'::regclass, 'authorizer_otps'::regclass) AND contype = 'u'; -- (b) standalone UNIQUE indexes (NOT backed by a constraint) — drop with DROP INDEX SELECT t.relname AS "table", i.relname AS name FROM pg_index ix JOIN pg_class i ON i.oid = ix.indexrelid JOIN pg_class t ON t.oid = ix.indrelid JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY (ix.indkey) WHERE t.relname IN ('authorizer_users', 'authorizer_otps') AND ix.indisunique AND NOT ix.indisprimary AND a.attname IN ('email', 'phone_number') AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = ix.indexrelid); ``` **2. Drop them** — `DROP CONSTRAINT` for every name from query (a), `DROP INDEX` for every name from query (b). For example: ```sql ALTER TABLE authorizer_users DROP CONSTRAINT IF EXISTS authorizer_users_email_key; ALTER TABLE authorizer_otps DROP CONSTRAINT IF EXISTS idx_authorizer_otps_phone_number; -- ...one line per name from query (a), across both tables, then for query (b): DROP INDEX IF EXISTS idx_authorizer_otps_email; ``` On **MySQL / MariaDB** these are unique indexes — list them with `SHOW INDEX FROM authorizer_users WHERE Non_unique = 0;` and drop with `ALTER TABLE authorizer_users DROP INDEX ;`. **SQLite** and the NoSQL backends are unaffected. :::note This only removes a constraint that v2 no longer uses. Duplicate emails and phone numbers are still rejected — the check now lives in the server, not the database. ::: --- ### 4. Deprecated GraphQL API Behavior These mutations exist for compatibility but **return an error** in v2; configure via CLI instead. | Mutation | v2 behavior | | ----------------- | ----------- | | `_update_env` | Returns error: `"deprecated. please configure env via cli args"` | | `_admin_signup` | Returns error: `"deprecated. please configure admin secret via cli args"` | | `_generate_jwt_keys` | Returns error: `"deprecated. please configure jwt keys via cli args"` | - **Admin secret:** set with `--admin-secret` at startup. - **JWT keys/type:** set with `--jwt-type`, `--jwt-secret`, or `--jwt-private-key` / `--jwt-public-key` at startup. - **All other env:** use the corresponding CLI flags when starting the server. If your app or dashboard calls `_update_env`, `_admin_signup`, or `_generate_jwt_keys`, remove or replace those calls and move configuration to startup arguments. --- ### 5. Docker changes in v2 - The v2 image uses **ENTRYPOINT** so the server receives CLI arguments at runtime. - Do **not** rely on env vars being read directly by the server; pass config as **arguments** to the container. Example: ```dockerfile ENTRYPOINT [ "./authorizer" ] CMD [] ``` Run with args: ```bash docker run -p 8080:8080 your-image \ --database-type=postgres \ --database-url="postgres://user:pass@host/db" \ --url=http://localhost:8080 \ --client-id=... \ --client-secret=... \ --admin-secret=... \ --encryption-key=your-encryption-key ``` Or use a script inside the image that maps env to flags and then runs `./authorizer ...`. --- ### 6. SDK and Client Libraries #### `@authorizerdev/authorizer-js` (v3) - **Version:** v2 uses **authorizer-js** `3.0.0-rc.1` (or compatible v3). - **Type renames (breaking):** - `SignupInput` to `SignUpRequest` - `LoginInput` to `LoginRequest` - `VerifyOtpInput` to `VerifyOTPRequest` - `MagicLinkLoginInput` to `MagicLinkLoginRequest` - **Build/output:** CJS/ESM paths may differ; check the package `exports` and your bundler. Upgrade: ```bash npm install @authorizerdev/authorizer-js@^3.3.0 # or pnpm add @authorizerdev/authorizer-js@^3.3.0 ``` #### `@authorizerdev/authorizer-react` (v2) - **Version:** use **authorizer-react** `^2.0.0` (or compatible v2) with **authorizer-js** v3. - **Breaking:** build system (tsdx to tsup), output paths (for example `dist/index.cjs`, `dist/index.mjs`), and **Node.js >= 18**. - **Types:** same renames as authorizer-js (for example `SignUpRequest`, `LoginRequest`). Example migration for type imports: ```ts // Old import { SignupInput, LoginInput } from '@authorizerdev/authorizer-js' // New import { SignUpRequest, LoginRequest } from '@authorizerdev/authorizer-js' ``` #### Other libraries - **authorizer-vue**, **authorizer-svelte**, **authorizer-go**, **authorizer-flutter-sdk**, and other repos under the Authorizer org will be updated for v2 compatibility; use versions that explicitly support Authorizer server v2 when available. --- ### 7. Migration Checklist - [ ] **Copy all existing v1 credentials** either from the dashboard or using the `_env` GraphQL query with your admin secret (see Step 1 above). Do this **before** shutting down v1. - [ ] Replace all v1 env / dashboard config with **CLI arguments** at server start. - [ ] Set **`--client-id`** and **`--client-secret`** (required). - [ ] Set **`--admin-secret`** and JWT options (`--jwt-type` and `--jwt-secret` or key pair) at startup. - [ ] Stop calling **`_update_env`**, **`_admin_signup`**, and **`_generate_jwt_keys`**; remove or replace with startup config. - [ ] Update Docker/K8s/deployment to pass config as **CLI args** (or via a wrapper that maps env to args). - [ ] Upgrade **@authorizerdev/authorizer-js** to v3 and **@authorizerdev/authorizer-react** to v2; update type names and Node version as needed. - [ ] Use **kebab-case** flags (for example `--database-url`) and avoid deprecated names (`database_url`, `env_file`, etc.). - [ ] Re-test admin login, JWT issuance, and any flows that previously depended on dashboard-updated env. --- ### Authorization (FGA) v2 adds an embedded **[OpenFGA](https://openfga.dev)** engine for relationship-based access control (ReBAC). You author an authorization **model** (OpenFGA DSL: types + relations), grant access with **relationship tuples** (for example `user:` is `viewer` of `document:1`), and have your apps check access with `check_permissions`. #### What's new - **Embedded OpenFGA engine.** Enabled by default when the main database is SQL (SQLite, Postgres, MySQL), reusing that same database. For NoSQL main databases (MongoDB, DynamoDB, …) it is off unless you set `--fga-store` (`sqlite` / `postgres` / `mysql` / `memory`) and `--fga-store-url`. - **Client query operations:** `check_permissions` and `list_permissions` (the subject defaults to the calling principal; an explicit `user` is honored only for super-admins or self). - **Admin GraphQL operations** (super-admin, `_fga_` prefix): `_fga_write_model`, `_fga_get_model`, `_fga_write_tuples`, `_fga_delete_tuples`, `_fga_read_tuples`, `_fga_list_users`, `_fga_expand`, and `_fga_reset`. Dashboard UI under **Authorization** → Step 1 Define model / Step 2 Grant access / Step 3 Test access. #### Adoption checklist - [ ] **Define the authorization model first** via the dashboard (Authorization → Step 1 Define model) or the `_fga_write_model` admin mutation. - [ ] **Grant access with tuples** using `_fga_write_tuples` (dashboard Step 2 Grant access) to relate subjects to objects. - [ ] **Adopt `check_permissions` incrementally** by adding access checks to one call site at a time (use `list_permissions` where it fits). Full reference: [Authorization (FGA)](../core/authorization). --- ## Contributing We're so excited you're interested in helping with Authorizer. We are happy to help you get started, even if you don't have any previous open-source experience. ### New to Open Source? 1. Take a look at [How to Contribute to an Open Source Project on GitHub](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github) 2. Go through the [Authorizer Code of Conduct](https://github.com/authorizerdev/authorizer/blob/main/.github/CODE_OF_CONDUCT.md) ### Where to ask questions? 1. Check our [Github Issues](https://github.com/authorizerdev/authorizer/issues) to see if someone has already answered your question. 2. Join our community on [Discord](https://discord.gg/Zv2D5h6kkK) and feel free to ask us your questions As you gain experience with Authorizer, please help answer other people's questions. ### What to work on? You can get started by taking a look at our [Github issues](https://github.com/authorizerdev/authorizer/issues) If you find one that looks interesting and no one else is already working on it, comment on that issue and start contributing. Please ask as many questions as you need, either directly in the issue or on [Discord](https://discord.gg/Zv2D5h6kkK). We're happy to help. #### Contributions that are ALWAYS welcome 1. More tests 2. Improved Docs 3. Improved error messages 4. Educational content like blogs, videos, courses ### Development Setup #### Prerequisites - OS: Linux or macOS or windows - Go: [Golang](https://golang.org/dl/) >= v1.15 #### Project Setup for Authorizer core 1. Fork the [authorizer](https://github.com/authorizerdev/authorizer) repository (**Skip this step if you have access to repo**) 2. `git clone https://github.com/authorizerdev/authorizer.git` 3. `cd authorizer` 4. Build the code `make clean && make` > Note: if you don't have [`make`](https://www.ibm.com/docs/en/aix/7.2?topic=concepts-make-command), you can `cd` into `server` dir and build using the `go build` command 5. Run binary with required flags: ```bash ./authorizer \ --database-type=sqlite \ --database-url=test.db \ --url=http://localhost:8080 \ --jwt-type=HS256 \ --jwt-secret=test \ --encryption-key=test-encryption-key \ --admin-secret=admin \ --client-id=123456 \ --client-secret=secret ``` Check all the supported flags [here](/core/server-config) #### Testing Make sure you test before creating PR. If you want to test for all the databases that authorizer supports you will have to run `mongodb` & `arangodb` instances locally. Setup mongodb & arangodb using Docker ```bash docker run --name mongodb -d -p 27017:27017 mongo docker run --name arangodb -d -p 8529:8529 -e ARANGO_ROOT_PASSWORD=root arangodb/arangodb:3.8.4 ``` > Note: If you are not making any changes in db schema / db operations, you can disable those db tests [here](https://github.com/authorizerdev/authorizer/blob/main/server/__test__/resolvers_test.go#L14) If you are adding new resolver, 1. create new resolver test file [here](https://github.com/authorizerdev/authorizer/tree/main/server/__test__) Naming convention filename: `resolver_name_test.go` function name: `resolverNameTest(s TestSetup, t *testing.T)` 2. Add your tests [here](https://github.com/authorizerdev/authorizer/blob/main/server/__test__/resolvers_test.go#L38) **Command to run tests:** ```sh make test ``` **Manual Testing:** For manually testing using graphql playground, you can paste following queries and mutations in your playground and test it ```graphql mutation Signup { signup( params: { email: "lakhan@yopmail.com" password: "test" confirm_password: "test" given_name: "lakhan" } ) { message user { id family_name given_name email email_verified } } } mutation ResendEamil { resend_verify_email( params: { email: "lakhan@yopmail.com", identifier: "basic_auth_signup" } ) { message } } query GetVerifyRequests { _verification_requests { id token expires identifier } } mutation VerifyEmail { verify_email(params: { token: "" }) { access_token expires_in user { id email given_name email_verified } } } mutation Login { login(params: { email: "lakhan@yopmail.com", password: "test" }) { access_token expires_in user { id family_name given_name email } } } query GetSession { session { access_token expires_in user { id given_name family_name email email_verified signup_methods created_at updated_at } } } mutation ForgotPassword { forgot_password(params: { email: "lakhan@yopmail.com" }) { message } } mutation ResetPassword { reset_password( params: { token: "", password: "test", confirm_password: "test" } ) { message } } mutation UpdateProfile { update_profile(params: { family_name: "samani" }) { message } } query GetUsers { _users { id email email_verified given_name family_name picture signup_methods phone_number } } mutation MagicLinkLogin { magic_link_login(params: { email: "test@yopmail.com" }) { message } } mutation Logout { logout { message } } mutation UpdateUser { _update_user( params: { id: "dafc9400-d603-4ade-997c-83fcd54bbd67" roles: ["user", "admin"] } ) { email roles } } mutation DeleteUser { _delete_user(params: { id: "b1e2c3d4-5678-90ab-cdef-1234567890ab" }) { message } } ```