This guide is for developers and for AI coding assistants. Assistants: read agents.md first, then follow the sections for your pattern in order and finish with the checklist in section 14.
1. Create the app and get its values
In the console: your first app with Set up Auth on the console home, later ones from Apps → Create app. Pick the app type from section 2 and enter the redirect URL (it can wait, but the app signs no one in until it has one). For a single-page app the console also allows that URL's origin to call the token endpoint. Set up Auth also creates your workspace's API with the permission app:use, and the role member, which grants it to everyone who signs up from then on. The API's audience is on the Connect step and the app page. Add more permissions under APIs and permissions, and under Roles, the roles that grant them. A Backend service picks its permissions when you create it.
Copy the values into environment variables with exactly these names:
| Variable | Where it comes from | Who needs it |
|---|---|---|
LEANTEL_ISSUER | Issuer on the app page, e.g. https://auth.leantel.dev | everything |
LEANTEL_CLIENT_ID | Client ID on the app page | apps that sign people in |
LEANTEL_CLIENT_SECRET | Shown once when the app is created or its secret is rotated | server apps only, never browser or mobile code |
LEANTEL_REDIRECT_URI | The URL Leantel returns to after sign-in, e.g. https://app.example.com/callback. Register it exactly under Redirect URLs | apps that sign people in |
LEANTEL_POST_LOGOUT_URI | Where people land after signing out. Register it under Sign-out redirect URLs | apps that sign people in |
LEANTEL_AUDIENCE | The API's audience (APIs and permissions): api_ then 3–40 lowercase letters, digits or inner hyphens, e.g. api_northwind-orders | apps that call or serve an API |
LEANTEL_WEBHOOK_SECRET | Webhooks → Signing secret | apps that receive webhooks |
Keep LEANTEL_CLIENT_SECRET in a secret store, such as AWS Systems Manager Parameter Store (SecureString), AWS Secrets Manager or HashiCorp Vault, and load it when your app starts. Never put it in source code or committed configuration. When the secret is rotated, the new one works within a minute and the previous one keeps working for 24 hours, so update your store within that window. Rotating again inside those 24 hours ends the oldest secret at once: do that to cut off a leaked secret.
Never commit these values. Commit a .env.example with the names and empty values.
Also register your app's sign-in start URL, the page in your app that starts sign-in (for example https://app.example.com/login). Leantel's emails, such as "You already have an account", link there; without it they link to the person's Leantel account page.
Redirect and sign-out URLs match byte for byte, never normalised: same scheme, host, port, path and query, no trailing-slash difference, lowercase host, no default port, no fragment or wildcard. They must be https, except:
- Mobile and desktop apps may register
http://127.0.0.1/callbackwithout a port; any port then matches (RFC 8252). - Web apps with a backend may also register exact
http://localhost:<port>/…URLs for local development. - Single-page apps may register exact
http://localhost:<port>/…andhttp://127.0.0.1:<port>/…URLs and origins in a development workspace only; production workspaces keep themhttps.
2. Pick your pattern
| Your app | Pattern | App type in the console |
|---|---|---|
| Server-rendered site, or a frontend with its own backend | The backend runs sign-in and keeps tokens; the browser only gets your own session cookie | Web app with a backend |
| Single-page app with no backend | Sign-in in the browser with PKCE; tokens in memory only | Single-page app |
| iOS, Android or desktop | The system browser (never a web view) with PKCE | Mobile or desktop app |
| Backend calling an API with no person signed in | Client credentials | Backend service |
If you can choose, use the first pattern. It keeps tokens out of the browser.
3. Sign in (web app with a backend)
Use a standard OpenID Connect library pointed at LEANTEL_ISSUER (it reads /.well-known/openid-configuration). Ready-to-run code: Go · TypeScript · JavaScript · Python · Java and Spring · Kotlin and Spring.
- Start sign-in. Redirect to the authorization endpoint with
response_type=code,client_id,redirect_uri,scope=openid email, a randomstateandnonce, and PKCE (code_challenge,code_challenge_method=S256). The access token is for your app's API; addresource=<LEANTEL_AUDIENCE>only to pick one when the app may call more than one API. Keep state, nonce and the PKCE verifier server-side or in a short-lived HttpOnly cookie. Optional:prompt=createopens the sign-up page,prompt=loginalways asks for credentials,prompt=nonenever shows a page (you geterror=login_requiredinstead),max_age,login_hint. - Handle the callback. Check
state, and check thatissequalsLEANTEL_ISSUER(RFC 9207). If the URL haserror, show a plain message, not the error code. Otherwise exchange thecode(with the PKCE verifier and your client secret, HTTP Basic preferred) within 60 seconds. A code works once. - Check the ID token. Your library verifies the signature, issuer, audience and expiry; check that
noncematches. The person issub, and their workspace in Leantel istenant_id.emailandemail_verifiedare there because you asked for theemailscope. - Start your own session. Store the user ID, tenant ID and tokens server-side; give the browser an HttpOnly, Secure, SameSite=Lax session cookie, then redirect to your app's home page. Never put tokens in
localStorage. - Call your API. Send the access token as
Authorization: Bearer <token>. Shortly before it expires, use the refresh token to get a new one, and save the new refresh token in place of the old one. - Sign out. End your session, revoke the refresh token at
revocation_endpoint, then redirect toend_session_endpointwithid_token_hintand a registeredpost_logout_redirect_uri.
Access tokens last 15 minutes by default. There is no offline_access scope: if refresh is on for your app, the code exchange returns a refresh token. Refresh tokens rotate: always keep only the newest one. Reusing an old refresh token more than 10 seconds after it was rotated ends that sign-in (its whole chain of refresh tokens is revoked), and the person has to sign in again.
4. Single-page apps
Use oauth4webapi. Your redirect URL's origin must be allowed to call the token endpoint (the console sets it from the redirect URL). Only the issuer and client ID go into browser code; there is no client secret.
import * as oauth from "oauth4webapi";
const issuer = new URL(import.meta.env.VITE_LEANTEL_ISSUER);
const client: oauth.Client = { client_id: import.meta.env.VITE_LEANTEL_CLIENT_ID };
const redirectUri = `${window.location.origin}/callback`;
let accessToken: string | undefined;
let refreshToken: string | undefined;
async function authorizationServer() {
return oauth.processDiscoveryResponse(issuer, await oauth.discoveryRequest(issuer));
}
export async function signIn(options: { signUp?: boolean } = {}) {
const server = await authorizationServer();
const verifier = oauth.generateRandomCodeVerifier();
const state = oauth.generateRandomState();
const nonce = oauth.generateRandomNonce();
sessionStorage.setItem("leantel_flow", JSON.stringify({ verifier, state, nonce }));
const url = new URL(server.authorization_endpoint!);
url.search = new URLSearchParams({
client_id: client.client_id,
redirect_uri: redirectUri,
response_type: "code",
scope: "openid email",
code_challenge: await oauth.calculatePKCECodeChallenge(verifier),
code_challenge_method: "S256",
state,
nonce,
...(options.signUp ? { prompt: "create" } : {}),
}).toString();
window.location.assign(url);
}
export async function completeSignIn() {
const server = await authorizationServer();
const flow = JSON.parse(sessionStorage.getItem("leantel_flow") ?? "{}");
sessionStorage.removeItem("leantel_flow");
const parameters = oauth.validateAuthResponse(server, client, new URL(window.location.href), flow.state);
const response = await oauth.authorizationCodeGrantRequest(server, client, oauth.None(), parameters, redirectUri, flow.verifier);
const result = await oauth.processAuthorizationCodeResponse(server, client, response, { expectedNonce: flow.nonce, requireIdToken: true });
accessToken = result.access_token;
refreshToken = result.refresh_token;
return oauth.getValidatedIdTokenClaims(result)!;
}
export async function callApi(input: string, init: RequestInit = {}) {
const send = () => fetch(input, { ...init, headers: { ...init.headers, Authorization: `Bearer ${accessToken}` } });
let response = await send();
if (response.status === 401 && refreshToken) {
const server = await authorizationServer();
const refreshed = await oauth.processRefreshTokenResponse(server, client, await oauth.refreshTokenGrantRequest(server, client, oauth.None(), refreshToken));
accessToken = refreshed.access_token;
refreshToken = refreshed.refresh_token ?? refreshToken;
response = await send();
}
return response;
}Tokens live in memory, so a page reload signs the person in again (a quick redirect while their Leantel session is active). Only the PKCE verifier, state and nonce may sit in sessionStorage, and only until the callback.
5. Mobile and desktop apps
Use AppAuth for iOS and Android. Always the system browser, never a web view. Redirect to a claimed https link (universal link or app link) or, on desktop, a loopback address. Register http://127.0.0.1/callback without a port; your app binds any free port at run time and sends http://127.0.0.1:<port>/callback, which matches (RFC 8252). Same parameters as section 3, with PKCE and no client secret. Keep the refresh token in the platform's secure storage (Keychain, Android Keystore).
6. Protect your API
Every request to your API carries Authorization: Bearer <access token>. Check the token where it arrives; never call Leantel to check it.
Option A: AWS API Gateway (HTTP API), no code. A JWT authorizer checks the token before your code runs:
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
}
variable "leantel_issuer" { type = string }
variable "leantel_audience" { type = string }
variable "orders_lambda_invoke_arn" { type = string }
resource "aws_apigatewayv2_api" "orders" {
name = "orders"
protocol_type = "HTTP"
}
resource "aws_apigatewayv2_authorizer" "leantel" {
api_id = aws_apigatewayv2_api.orders.id
name = "leantel"
authorizer_type = "JWT"
identity_sources = ["$request.header.Authorization"]
jwt_configuration {
issuer = var.leantel_issuer
audience = [var.leantel_audience]
}
}
resource "aws_apigatewayv2_integration" "orders" {
api_id = aws_apigatewayv2_api.orders.id
integration_type = "AWS_PROXY"
integration_uri = var.orders_lambda_invoke_arn
payload_format_version = "2.0"
}
resource "aws_apigatewayv2_route" "list_orders" {
api_id = aws_apigatewayv2_api.orders.id
route_key = "GET /orders"
target = "integrations/${aws_apigatewayv2_integration.orders.id}"
authorization_type = "JWT"
authorizer_id = aws_apigatewayv2_authorizer.leantel.id
}Your Lambda reads the claims from event.requestContext.authorizer.jwt.claims. To require a permission on a route, add authorization_scopes = ["app:use"]; a token without it gets 403.
Option B: in your code. In Go, use authverify (go get github.com/leantel/authverify, Go 1.25 or later): authverify.Middleware(issuer, audience) checks the token and authverify.FromContext(ctx) returns the claims. For other languages, see the quickstarts. Whatever library you use, it must check all of these:
- Algorithm is
RS256only, and the key comes from<LEANTEL_ISSUER>/.well-known/jwks.json(cache it; refetch on an unknownkid, at most once a minute). - Header
typisat+jwt(orapplication/at+jwt, RFC 9068). This rejects ID tokens sent by mistake. Spring Security's default validator only allowsJWT; the Java and Kotlin quickstarts show how to allowat+jwt. issequalsLEANTEL_ISSUERexactly,audcontainsLEANTEL_AUDIENCE,expandiatare present, andexp,nbfandiathold (allow 60 seconds of clock skew).sub,jti,client_idandtenant_idare not empty.- If the route needs a permission, it is in
scope. Missing token or bad token → 401; valid token without the permission → 403.
7. What's in an access token
| Claim | Meaning |
|---|---|
sub | The person (usr_…), or the client ID for a backend service |
tenant_id | Your workspace in Leantel. Use this, never a tenant ID from the request |
scope | Space-separated permissions, e.g. openid app:use |
roles | The person's roles, e.g. ["support"] (absent if none) |
utype | User type you set, e.g. staff (absent if none) |
client_id | The app the token was issued to |
authz_ver | Version of your workspace's roles and permissions when the token was issued |
iss, aud, exp, iat, jti | Standard (RFC 9068); aud is your API's audience |
A person gets a permission only through a role that grants it, so someone with no roles gets no permissions and your permission checks return 403. In a workspace made with Set up Auth, people who sign up get its role member, and with it app:use; people added before that have only the roles you gave them. If you request no permissions, the token carries every permission the person's roles grant for your API; list them in scope to ask for fewer. If the scope would pass 2 KB, the request fails with invalid_scope: list the permissions you need. Permissions say what someone may do in general. Ownership ("is this their order?") stays in your code. Role and permission changes reach new tokens within a minute; a token already issued keeps its permissions until it expires (15 minutes by default). A refresh drops permissions the person has lost but never adds new ones: they get those at their next sign-in.
8. Webhooks
Leantel posts signed JSON to your webhook URL when people sign up or their details change (Webhooks page). Each request has Auth-Event-Id, Auth-Event-Type and Auth-Signature: t=<unix seconds>,v1=<hex>. The body is {"id":"evt_…","type":"user.registered","tenant_id":"ten_…","occurred_at":"2026-10-01T17:04:05Z","data":{…}}.
To verify: compute HMAC-SHA256 with your signing secret over <t>.<raw request body>, compare it to v1 in constant time, and reject a t more than 5 minutes from your clock, in the past or the future. Use the raw body bytes, not re-serialised JSON. Some proxies split headers at commas: join every Auth-Signature value with , before parsing. Delivery is at least once and in any order: skip events whose Auth-Event-Id (the body's id) you've already handled. Reply with any 2xx within 5 seconds and do the work after; a failed delivery is retried 5 times over about 9 hours (after 1 min, 5 min, 30 min, 2 h and 6 h), then parked until it's retried from the console.
| Event | data |
|---|---|
user.registered | user_id, email, utype, roles, profile (your sign-up fields), method (password, google, invite, seed, authctl) |
user.email_verified | user_id, email |
user.email_changed | user_id, old_email, new_email |
user.roles_changed | user_id, roles, utype |
user.status_changed | user_id, from, to |
user.password_changed | user_id |
user.deleted | user_id |
ping | {}; sent by Send test event in the console, whatever events you chose |
Store sign-up fields from user.registered in your own database, keyed by user_id (the same value as sub).
9. Backend services (no person signed in)
Create a Backend service app and tick the permissions it needs on the API (add them under APIs and permissions first), then POST to the token endpoint with grant_type=client_credentials, scope=<the permissions you need, space-separated> and HTTP Basic auth (client ID and secret); add resource=<audience> only to pick one when the app may call more than one API. Nothing requested means an empty scope. The response has an access token only (no refresh or ID token), and its sub is the client ID. Cache the access token until shortly before expires_in.
10. Endpoints
Read them from <LEANTEL_ISSUER>/.well-known/openid-configuration (OpenID Connect Discovery); don't hard-code them.
| Discovery field | Path today | Use |
|---|---|---|
authorization_endpoint | /oauth/authorize | Start sign-in or sign-up (GET, browser redirect) |
token_endpoint | /oauth/token | Exchange a code, refresh, client credentials (POST, form-encoded) |
userinfo_endpoint | /oauth/userinfo | sub, tenant_id, utype, plus email and email_verified with the email scope (GET or POST, bearer token with openid) |
revocation_endpoint | /oauth/revoke | Revoke a refresh token (RFC 7009); always answers 200. Access tokens can't be revoked |
end_session_endpoint | /oauth/logout | Sign out (GET, browser redirect) |
jwks_uri | /.well-known/jwks.json | Public keys for checking tokens |
Supported: response_type code; grants authorization_code, refresh_token, client_credentials; PKCE S256 only; scopes openid, profile, email plus your API's permissions; client authentication none (public apps), client_secret_basic (preferred) or client_secret_post; signing RS256.
11. When something goes wrong
The token endpoint answers errors as JSON with error and error_description (RFC 6749 §5.2). Show the person a plain message, not the error code; log error and the X-Request-ID response header, never tokens or secrets.
| What you see | Why |
|---|---|
| Leantel shows "We can't sign you in from here." | The redirect URL isn't registered exactly (scheme, host, path, no trailing slash difference), or the app is disabled |
Callback has error=invalid_request | PKCE is missing or not S256 |
Callback has error=invalid_scope or invalid_target | A scope your app may not ask for, or a resource that isn't one of your app's APIs |
Callback has error=login_required | You sent prompt=none and the person has no Leantel session |
invalid_client (401) | Wrong or missing client secret, or the app is disabled |
invalid_grant when exchanging the code | The code is older than 60 seconds or already used, redirect_uri differs, or the PKCE verifier is wrong |
invalid_grant when refreshing | An older refresh token was reused (keep only the newest), or the person was suspended or changed their password |
unauthorized_client | The app may not use that grant (only Backend service apps use client_credentials) |
invalid_target | The resource isn't an API your app is allowed to call |
invalid_scope | A scope your app may not ask for, or the token's scope would pass 2 KB: list the permissions you need |
429 slow_down | Too many requests: wait and retry with backoff |
| 401 from API Gateway with a token that looks fine | aud differs from the authorizer's audience, or the issuer differs (check for a trailing slash) |
| 403 from API Gateway, or from your API, with a valid token | The token's scope lacks the route's permission. Give the person a role that grants it; it arrives at their next sign-in |
A client_credentials token has an empty scope | Request the permissions with scope (for example scope=app:use); nothing requested means none are granted |
| 401 from Spring with a valid token | Spring's default validator rejects typ: at+jwt; see the Java or Kotlin quickstart |
| API calls fail about 15 minutes after sign-in | The app never refreshes, or keeps an old refresh token after rotation; save the new pair every time |
| Browser app: token request blocked by CORS | Its origin isn't allowed (scheme and host only, e.g. https://app.example.com, no path or slash) |
| Sign-out ends on Leantel's "signed out" page | The sign-out URL isn't registered exactly, or id_token_hint is missing |
| A role change doesn't show up | Access tokens last up to 15 minutes; a refresh drops lost permissions, but added ones arrive at the next sign-in |
12. What to store, and what never to store
| Store | Where |
|---|---|
sub and tenant_id | Your database, as the key for your own user records |
| Access, refresh and ID tokens (web app with a backend) | Server-side session store, behind an HttpOnly, Secure, SameSite=Lax cookie |
| Access and refresh tokens (single-page app) | Memory only |
| Refresh token (mobile or desktop) | Keychain or Android Keystore |
| Client secret, webhook signing secret | A secret store, loaded at start-up |
Never store: tokens in localStorage, sessionStorage, cookies set from JavaScript or URLs; passwords (Leantel's pages collect them); the client secret in browser or mobile code, committed files or logs; a tenant ID taken from request input.
13. Test on dev
- Point
LEANTEL_ISSUERat the issuer you were given and open<LEANTEL_ISSUER>/.well-known/openid-configuration: itsissuermust equalLEANTEL_ISSUERexactly. - Sign up a test person with
prompt=create, then sign in, refresh and sign out. - Check the token's
scope: a person who signed up hasapp:usethrough the rolemember; one with no roles has no permissions. - Call your API with no token (401), a token for another audience (401) and, on a route that needs a permission, a token without it (403).
- Webhooks: press Send test event on the Webhooks page and check your endpoint answers the
pingwith 2xx; then send a body with a changed byte and check it's rejected.
The API Gateway authorizer needs the deployed (https) issuer; it can't reach a local one.
14. Checklist
- Endpoints come from discovery; the issuer is exact, with no trailing slash.
- Every sign-in uses PKCE
S256,stateandnonce; the callback checksstateandiss. - The redirect and sign-out URLs are registered exactly as the app sends them.
- The client secret is only in server code, loaded from a secret store;
.env.examplehas empty values. - No token in
localStorageorsessionStorage; server apps use an HttpOnly session cookie. - Refresh saves the new refresh token every time; sign-out revokes it and goes to
end_session_endpoint. - Every API route checks the token (section 6), and its permission where it needs one: 401 without a valid token, 403 without the permission.
- The tenant comes from the token's
tenant_id, never from the request. - Webhooks are verified on the raw body, deduplicated on
Auth-Event-Id, and answered within 5 seconds. - Tests cover: valid token passes, wrong audience fails, missing permission fails, bad webhook signature fails.
15. Import users from another provider
Moving from Auth0, Cognito or your own database: a Backend service app with admin:users:write POSTs a JSON Lines body (up to 10,000 lines and 5 MB) to /v1/admin/users/imports, one person per line: {"email": "ada@example.com", "email_verified": true, "utype": "staff", "roles": ["admin"]} (omitted utype and roles take your workspace defaults). The answer is 202 with an import_id; GET the same path followed by /<import_id> until status is DONE, then read created, skipped (emails that already exist) and failed (line and reason, the first 100). Imported people have no password: they sign in through a password reset email, Google or a passkey. Password hashes can't be imported yet: a line with password_hash fails with unsupported_hash. Each new person sends a user.registered webhook.