Authentication Guide
Idenplane implements OAuth 2.0 and OpenID Connect (OIDC) for secure authentication and authorization. This guide covers all supported flows, security considerations, and implementation patterns.
Supported Flows
Idenplane supports the following OAuth 2.0 flows:
| Flow | Use Case | Security Level |
|---|---|---|
| Authorization Code + PKCE | Web/Mobile apps | Highest |
| Client Credentials | Machine-to-machine | High |
| Device Authorization | CLI tools, Smart TVs | High |
| Refresh Token | Token renewal | High |
The Resource Owner Password Credentials grant is deprecated by OAuth 2.1 and will be removed in a future release. Please migrate to the Authorization Code + PKCE flow.
Authorization Code Flow
The Authorization Code flow is the recommended OAuth 2.0 flow for all applications. It provides the highest security when combined with PKCE (Proof Key for Code Exchange).
Flow Diagram
Step 1: Generate PKCE Parameters
Before redirecting the user, generate a code verifier and challenge:
- JavaScript
- Python
- Kotlin
// Generate a random code verifier (43-128 characters)
function generateCodeVerifier() {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return btoa(String.fromCharCode(...array))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
// Generate code challenge from verifier using SHA-256
async function generateCodeChallenge(verifier) {
const encoder = new TextEncoder();
const data = encoder.encode(verifier);
const digest = await crypto.subtle.digest('SHA-256', data);
return btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
// Usage
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
// Store verifier securely (sessionStorage is recommended)
sessionStorage.setItem('code_verifier', codeVerifier);
import secrets
import hashlib
import base64
def generate_code_verifier(length=64):
"""Generate a random code verifier."""
return secrets.token_urlsafe(length)[:128]
def generate_code_challenge(verifier):
"""Generate code challenge from verifier using SHA-256."""
digest = hashlib.sha256(verifier.encode()).digest()
return base64.urlsafe_b64encode(digest).decode().rstrip('=')
# Usage
code_verifier = generate_code_verifier()
code_challenge = generate_code_challenge(code_verifier)
import java.security.SecureRandom
import java.util.Base64
import java.security.MessageDigest
fun generateCodeVerifier(): String {
val random = SecureRandom()
val bytes = ByteArray(32)
random.nextBytes(bytes)
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
}
fun generateCodeChallenge(verifier: String): String {
val digest = MessageDigest.getInstance("SHA-256")
val hash = digest.digest(verifier.toByteArray())
return Base64.getUrlEncoder().withoutPadding().encodeToString(hash)
}
Step 2: Redirect to Authorization Endpoint
Construct the authorization URL and redirect the user:
const authUrl = new URL(
'http://localhost:3000/realms/my-realm/protocol/openid-connect/auth'
);
authUrl.searchParams.set('client_id', 'my-app');
authUrl.searchParams.set('redirect_uri', 'https://myapp.com/callback');
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('scope', 'openid profile email');
authUrl.searchParams.set('state', generateRandomState());
authUrl.searchParams.set('code_challenge', codeChallenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
// Optional parameters
authUrl.searchParams.set('nonce', generateRandomNonce());
authUrl.searchParams.set('acr_values', 'urn:idenplane:acr:mfa');
authUrl.searchParams.set('login_hint', 'user@example.com');
// Redirect user
window.location.href = authUrl.toString();
Authorization Parameters
| Parameter | Required | Description |
|---|---|---|
client_id | Yes | Your application's client ID |
redirect_uri | Yes | URL to redirect after authorization |
response_type | Yes | Must be code for authorization code flow |
scope | Yes | Space-separated scopes (include openid) |
state | Recommended | Random string to prevent CSRF attacks |
code_challenge | Public clients | PKCE challenge (SHA-256 hash of verifier); required for public clients, recommended for all |
code_challenge_method | With code_challenge | Must be S256 |
nonce | Recommended | Random string included in ID token |
acr_values | No | Requested Authentication Context Class Reference |
login_hint | No | Pre-fill username field |
prompt | No | login, consent or none |
Step 3: Handle the Callback
After authorization, Idenplane redirects to your redirect_uri with an authorization code:
// Extract code and state from URL
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
const state = params.get('state');
const error = params.get('error');
// Validate state to prevent CSRF
const storedState = sessionStorage.getItem('oauth_state');
if (state !== storedState) {
throw new Error('State mismatch - potential CSRF attack');
}
// Exchange code for tokens
if (code) {
const tokenResponse = await exchangeCodeForTokens(code);
// Store tokens and clean up
sessionStorage.removeItem('code_verifier');
sessionStorage.removeItem('oauth_state');
}
Step 4: Exchange Code for Tokens
Send the authorization code to the token endpoint:
curl -X POST "http://localhost:3000/realms/my-realm/protocol/openid-connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=authorization_code" \
-d "client_id=my-app" \
-d "code=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." \
-d "redirect_uri=https://myapp.com/callback" \
-d "code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
Response:
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"expires_in": 300,
"refresh_token": "rt_8xq2k3j5h7...",
"token_type": "Bearer",
"id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"scope": "openid profile email"
}
Complete Authorization Code Example
The JavaScript SDK does the PKCE, state and code exchange for you:
import { IdenplaneClient } from 'idenplane-sdk';
const client = new IdenplaneClient({
url: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'https://myapp.com/callback',
});
// Login button: generates the PKCE verifier and state, then redirects
async function login(): Promise<void> {
await client.login({ scope: ['openid', 'profile', 'email'] });
}
// On the /callback page: checks state, exchanges the code with the verifier
async function onCallback(): Promise<void> {
const ok = await client.handleCallback();
if (ok) {
const accessToken = client.getAccessToken();
// ...call your API with the token
}
}
Client Credentials Grant
The Client Credentials grant is used for machine-to-machine communication where there is no user interaction. Service accounts use this flow to obtain access tokens.
When to Use
- Backend services calling other backend services
- CI/CD pipelines and automation scripts
- Microservices communicating with each other
- CLI tools with service accounts
Request
curl -X POST "http://localhost:3000/realms/my-realm/protocol/openid-connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials" \
-d "client_id=my-service" \
-d "client_secret=${CLIENT_SECRET}" \
-d "scope=read write"
Response:
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"expires_in": 300,
"token_type": "Bearer",
"scope": "read write"
}
Service Account Setup
- Create a client in Idenplane Admin Console
- Set the Access Type to
Confidential(service accounts) - Configure the allowed grant types (ensure
client_credentialsis enabled) - Assign roles to the service account user
// Service account token example
async function getServiceToken(): Promise<string> {
const response = await fetch(
'http://localhost:3000/realms/my-realm/protocol/openid-connect/token',
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: process.env.IDENPLANE_CLIENT_ID,
client_secret: process.env.IDENPLANE_CLIENT_SECRET,
scope: 'read write',
}),
}
);
const { access_token } = await response.json();
return access_token;
}
// Use the token to call your own resource server.
// (A client_credentials token cannot call Idenplane's admin API; that needs
// the admin API key or an admin user's token.)
async function callProtectedAPI(token: string) {
const response = await fetch('https://api.example.com/reports', {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response.json();
}
Device Authorization Grant
The Device Authorization grant (RFC 8628) is designed for devices with limited input capabilities, such as CLI tools, smart TVs, or IoT devices.
Flow Overview
- Device requests authorization from Idenplane
- User enters user code on another device
- Device polls for authorization completion
- Device receives tokens
Step 1: Request Device Code
curl -X POST "http://localhost:3000/realms/my-realm/protocol/openid-connect/auth/device" \
-d "client_id=my-cli-tool"
my-cli-tool is a public client, so its client_id is enough. A confidential client also sends its credentials, as it does at the token endpoint.
Response:
{
"device_code": "GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS...",
"user_code": "WDJB-MJHT",
"verification_uri": "https://auth.example.com/realms/my-realm/device",
"verification_uri_complete": "https://auth.example.com/realms/my-realm/device?user_code=WDJB-MJHT",
"expires_in": 600,
"interval": 5
}
Step 2: Display Instructions to User
Show the user the verification URI and user code:
function displayDeviceAuthorization(deviceResponse: DeviceCodeResponse) {
console.log(`
To authorize this device:
1. Visit: ${deviceResponse.verification_uri_complete}
2. Enter code: ${deviceResponse.user_code}
This code expires in ${deviceResponse.expires_in / 60} minutes.
`);
}
Step 3: Poll for Authorization
async function pollForAuthorization(
deviceCode: string,
interval: number
): Promise<TokenResponse> {
while (true) {
await sleep(interval * 1000);
const response = await fetch(
'http://localhost:3000/realms/my-realm/protocol/openid-connect/token',
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
client_id: 'my-cli-tool',
device_code: deviceCode,
}),
}
);
const data = await response.json();
switch (data.error) {
case 'authorization_pending':
// User hasn't completed authorization yet
continue;
case 'slow_down':
// Increase polling interval
interval += 5;
continue;
case 'access_denied':
throw new Error('Authorization was denied');
case 'expired_token':
throw new Error('Device code expired');
default:
// Success or other error
return data;
}
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
The device authorization grant does not support MFA or step-up authentication. For applications requiring higher assurance, use the Authorization Code flow.
Refreshing Tokens
Access tokens expire after the configured lifespan (default: 5 minutes). Use refresh tokens to obtain new access tokens without re-authentication.
Refresh Token Request
curl -X POST "http://localhost:3000/realms/my-realm/protocol/openid-connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=refresh_token" \
-d "client_id=my-app" \
-d "refresh_token=rt_8xq2k3j5h7..."
Response:
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"expires_in": 300,
"refresh_token": "rt_new_8xq2k3j5h7...", // New refresh token (token rotation)
"token_type": "Bearer",
"scope": "openid profile email"
}
Token Rotation
Idenplane uses refresh token rotation by default. Each refresh token can only be used once, and a new refresh token is issued with each refresh. This provides enhanced security by detecting token theft through reuse attempts.
class TokenManager {
private refreshToken: string | null = null;
private client: IdenplaneClient;
async refreshAccessToken(): Promise<void> {
if (!this.refreshToken) {
throw new Error('No refresh token available');
}
try {
const response = await fetch(
`${this.client.config.url}/realms/${this.client.config.realm}/protocol/openid-connect/token`,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'refresh_token',
client_id: this.client.config.clientId,
refresh_token: this.refreshToken,
}),
}
);
if (!response.ok) {
throw new Error('Token refresh failed');
}
const tokens = await response.json();
// Update stored refresh token (new rotation)
this.refreshToken = tokens.refresh_token;
this.storeTokens(tokens);
} catch (error) {
// Refresh token compromised or expired
this.clearTokens();
throw error;
}
}
private storeTokens(tokens: TokenResponse) {
// Store tokens securely
sessionStorage.setItem('access_token', tokens.access_token);
if (tokens.refresh_token) {
sessionStorage.setItem('refresh_token', tokens.refresh_token);
}
}
private clearTokens() {
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('refresh_token');
}
}
Step-Up Authentication
Step-up authentication allows requesting a higher assurance level for sensitive operations. Idenplane supports ACR (Authentication Context Class Reference) values to indicate the required authentication strength.
ACR Values
| ACR Value | Description | Use Case |
|---|---|---|
urn:idenplane:acr:password | Password authentication only | Standard login |
urn:idenplane:acr:mfa | Multi-factor authentication | Sensitive operations |
urn:idenplane:acr:webauthn | Passkey (WebAuthn) authentication | Highest assurance |
Requesting Step-Up
// Request step-up authentication during authorization
const authUrl = new URL(
'http://localhost:3000/realms/my-realm/protocol/openid-connect/auth'
);
authUrl.searchParams.set('client_id', 'my-app');
authUrl.searchParams.set('redirect_uri', 'https://myapp.com/callback');
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('scope', 'openid profile email');
authUrl.searchParams.set('acr_values', 'urn:idenplane:acr:mfa');
// User will be prompted for MFA if not already authenticated with MFA
ID Token ACR Claim
After step-up authentication, the ID token includes the ACR claim:
{
"iss": "http://localhost:3000/realms/my-realm",
"sub": "user-uuid-123",
"aud": "my-app",
"acr": "urn:idenplane:acr:mfa",
"amr": ["pwd", "otp"],
"exp": 1620000000
}
Verifying Step-Up in API
import jwt from 'jsonwebtoken';
async function verifyAccessTokenWithStepUp(
token: string,
requiredAcr: string
): Promise<boolean> {
// Decode without verification to get claims
const claims = jwt.decode(token, { complete: true });
if (!claims || !claims.payload) {
return false;
}
// Get ACR strength comparison
const tokenAcrStrength = getAcrStrength(claims.payload.acr);
const requiredAcrStrength = getAcrStrength(requiredAcr);
return tokenAcrStrength >= requiredAcrStrength;
}
function getAcrStrength(acr: string): number {
const strengths: Record<string, number> = {
'urn:idenplane:acr:password': 1,
'urn:idenplane:acr:mfa': 2,
'urn:idenplane:acr:webauthn': 3,
};
return strengths[acr] || 0;
}
Session Management
Idenplane manages sessions to track user authentication state and enforce concurrent session limits.
Session Lifecycle
Concurrent Session Limits
Realms can enforce maximum concurrent sessions per user:
| Setting | Behavior |
|---|---|
maxSessionsPerUser: 0 | Unlimited sessions |
maxSessionsPerUser: 10 | Maximum 10 active sessions (the default) |
When a user exceeds the limit, the oldest sessions are automatically evicted (FIFO). The limit applies separately to OAuth sessions (refresh tokens) and to browser SSO sessions.
Offline sessions (created with the offline_access scope) are outside the limit: they don't count toward it, a new sign-in never evicts one, and creating one evicts nothing. Since 0.12.0; before, a user's offline sessions counted, and enough sign-ins evicted them.
Session Cookies
Idenplane uses an IDENPLANE_SESSION cookie for browser-based SSO:
// Cookie configuration (set by Idenplane server)
const cookieConfig = {
name: 'IDENPLANE_SESSION',
httpOnly: true, // Not accessible by JavaScript
secure: true, // Never sent over plain HTTP
sameSite: 'lax', // Sent on top-level navigations from other sites (SSO, logout)
path: '/realms/{realm}', // Scoped to one realm
maxAge: undefined, // Browser session; 30 days with "remember me"
};
Logout
RP-initiated logout is a browser redirect. It ends the SSO session in the IDENPLANE_SESSION cookie:
https://auth.example.com/realms/my-realm/protocol/openid-connect/logout
?id_token_hint=<the user's ID token>
&post_logout_redirect_uri=https://myapp.com/signed-out
&state=<optional>
post_logout_redirect_uri must be registered on the client.
async function logout(accessToken: string, refreshToken: string) {
// Revoke refresh token (the client authenticates; a public client sends its client_id)
await fetch(
'http://localhost:3000/realms/my-realm/protocol/openid-connect/revoke',
{
method: 'POST',
body: new URLSearchParams({ token: refreshToken, client_id: 'my-app' }),
}
);
// Clear local storage
sessionStorage.clear();
localStorage.removeItem('idenplane_tokens');
}
Back-Channel Logout
A client that registers a backchannelLogoutUri (OpenID Connect Back-Channel Logout 1.0) is told when a session it holds ends, by a server-to-server POST of a signed logout token to that URI. Idenplane sends one whenever an OAuth session ends:
| How the session ended | Since |
|---|---|
The user signs out (/protocol/openid-connect/logout) | earlier |
An admin ends one session (DELETE /admin/realms/{realm}/sessions/{id}) or continuous verification ends a risky one | 0.13.0 |
The user is signed out everywhere: admin "sign out all sessions" (DELETE /admin/realms/{realm}/users/{id}/sessions), disabling or deleting the user, SCIM deactivation, and every credential change (a password set, reset or changed, second factors removed) | 0.13.0 |
The SSO idle timeout (ssoSessionIdleTimeout): a session whose refresh token went unused for longer ends at the next hourly clean-up | 0.13.0 |
A new sign-in evicts the user's oldest session at maxSessionsPerUser | 0.13.0 |
| A refresh token is reused (a sign of theft, RFC 9700 §4.14), which ends its whole session | 0.13.0 |
| An authorization code is replayed by its client, which ends the session issued from it (RFC 6749 §4.1.2) | 0.13.0 |
Only the clients the session was used with are told, not every client of the realm: the clients its refresh tokens were issued to. A session whose refresh tokens record no client (tokens issued before refresh tokens recorded one) falls back to the client of the authorization code it was created from. When neither records a client (access tokens are not stored, so they cannot say), every client of the realm with a backchannelLogoutUri is told, as every logout did before 0.13.0; each token names the session, so a client that never saw it ignores it. A session with no refresh token at all, such as an impersonation session, was never given to a client and is not announced.
The request is Content-Type: application/x-www-form-urlencoded with one parameter, logout_token, a JWT signed with the realm's active key (RS256, verifiable with the realm's JWKS) and typed logout+jwt:
{
"iss": "https://auth.example.com/realms/my-realm",
"aud": "my-app",
"sub": "<user id>",
"sid": "<session id: the sid claim of the session's ID tokens>",
"iat": 1795000000,
"exp": 1795000120,
"jti": "<unique id>",
"events": { "http://schemas.openid.net/event/backchannel-logout": {} }
}
- Each token names one ended session (
sid) and its user (sub), one token per session and client. The one exception: when a user is signed out everywhere, a client withoutbackchannelLogoutSessionRequired(it is on by default) gets a single token withsubonly, which per the specification means "end every session of this user". A session ended on its own never produces asub-only token, so the client's other sessions for the user are left alone. - There is never a
nonce, so a logout token cannot be mistaken for an ID token. Check the signature,iss,aud,iat/exp, theeventsmember and the absence ofnonce, as the specification describes. - Offline sessions are included. Signing a user out everywhere revokes their offline tokens too, so a client that keeps one for background work is told that the session (
sid) is gone. A user's own sign-out is different: signing out of a session leaves the user's other sessions alone, offline ones included, and a logout that names only the user (an ID token or logout token withsuband nosid) ends their sessions but not their offline sessions (since 0.13.0). Signing out with the offline sign-in's own ID token or refresh token does end that offline session: it is the session named (see the threat model). - Browser SSO sessions (the
IDENPLANE_SESSIONcookie) are not tied to a client's session, so ending one, or one expiring, sends nothing. A session reaching its maximum lifetime (refreshTokenLifespan,offlineTokenLifespan) sends nothing either: the client already knows the refresh token's lifetime.
Where tokens may go. Back-channel URIs on the operator's own network (http://app.internal/..., private and loopback addresses) are allowed: relying parties often run there. Link-local and cloud instance-metadata addresses are refused (169.254.0.0/16, which includes 169.254.169.254; fe80::/10; AWS's fd00:ec2::254; Alibaba's 100.100.100.200; Oracle's 192.0.0.192; and the same addresses embedded in IPv6), checked on the URI's host and on every address its name resolves to, at each delivery. The refusal is logged and nothing is sent. Set BACKCHANNEL_LOGOUT_ALLOW_LINK_LOCAL=true to allow them. Starting with 0.13.1, the connection is pinned to the validated IP address while the original hostname is retained for HTTP Host and TLS certificate verification. DNS rebinding cannot change the connection target. Redirects are not followed, and the 10-second delivery deadline includes DNS resolution. Pinning also applies when the link-local override is enabled. Version 0.13.0 checks addresses but does not pin the connection.
Delivery is fire-and-forget, after the sign-out has been committed: the admin call or sign-out never waits for, or fails because of, a client. Each POST has a 10-second timeout and does not follow redirects; at most 8 are in flight at once per server. A failure (a network error, a timeout, or a non-2xx answer) is logged as a warning by BackchannelLogoutService and not retried: the token is valid for two minutes, and the client's refresh token and session are already revoked, so a client that missed the token finds out at its next refresh or UserInfo call.
Security Best Practices
Always Use PKCE
OAuth 2.1 requires PKCE for all authorization code flows. Idenplane enforces this for public clients.
Protect Against CSRF
// Generate and store state for CSRF protection
function generateState(): string {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return btoa(String.fromCharCode(...array))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
const state = generateState();
sessionStorage.setItem('oauth_state', state);
// On callback, verify state matches
const returnedState = new URLSearchParams(window.location.search).get('state');
if (returnedState !== sessionStorage.getItem('oauth_state')) {
throw new Error('CSRF attack detected');
}
Use Secure Token Storage
| Storage | Use Case | Security |
|---|---|---|
memory | Single-page apps, short-lived | Best (cleared on page close) |
sessionStorage | Multi-tab browsing | Good (isolated per tab) |
localStorage | Persistent sessions | Caution (accessible to JS) |
HttpOnly cookies | Server-side apps | Best (not accessible to JS) |
Validate Redirect URIs
Configure exact redirect URIs in your client configuration:
{
"redirectUris": [
"https://myapp.com/callback",
"https://staging.myapp.com/callback"
]
}
Token Expiration
| Token Type | Default Lifespan | Recommended |
|---|---|---|
| Access Token | 5 minutes | 5-15 minutes |
| Refresh Token | 30 minutes | 30-60 minutes |
| ID Token | 5 minutes | Match access token |
Error Handling
OAuth Error Responses
interface OAuthError {
error: string; // Error code
error_description?: string; // Human-readable description
}
async function handleTokenRequest() {
try {
const response = await fetch(tokenUrl, options);
const data = await response.json();
if (!response.ok && data.error) {
switch (data.error) {
case 'invalid_grant':
// Authorization code expired or already used
// Clear stored code and re-initiate flow
break;
case 'invalid_client':
// Client authentication failed
// Check client_id and client_secret
break;
case 'invalid_request':
// Malformed request
// Check request parameters
break;
case 'unauthorized_client':
// Grant type not allowed for client
break;
case 'unsupported_grant_type':
// Server doesn't support this grant type
break;
}
throw new OAuthError(data);
}
return data;
} catch (error) {
// Handle network errors
if (error instanceof TypeError) {
throw new Error('Network error - check connection');
}
throw error;
}
}
Error Flow Detection
// Detect and handle error responses from authorization
function parseCallback(): { code?: string; error?: string; state?: string } {
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
const error = params.get('error');
const errorDescription = params.get('error_description');
const state = params.get('state');
if (error) {
const errorMessages: Record<string, string> = {
'access_denied': 'User denied the authorization request',
'invalid_request': 'Invalid authorization request parameters',
'unauthorized_client': 'This client is not authorized',
'unsupported_response_type': 'Server does not support this response type',
'server_error': 'Authorization server encountered an error',
};
throw new Error(
errorMessages[error] || `Authorization error: ${errorDescription}`
);
}
return { code, state };
}
Identity Providers
Idenplane can delegate authentication to an external provider, so users sign in with an account they already have. Providers are configured per realm, under Identity Providers in the admin console.
What this covers
These endpoints handle OpenID Connect providers — Okta, Auth0, Microsoft Entra, Google, another Keycloak or Idenplane, anything that speaks OIDC — and SAML 2.0 identity providers. providerType is oidc (the default), oauth2 (a plain OAuth 2.0 provider such as GitHub; the broker treats it like oidc) or saml. Any other value is refused with 400. A saml provider takes its settings in samlConfig instead of the OAuth fields: see Sign in with a SAML identity provider.
Two neighbouring features are managed separately:
- Idenplane as a SAML 2.0 identity provider for downstream service providers (the opposite direction): the console lists those under SAML Providers
- LDAP and other external user stores live under User Federation, which synchronises users rather than delegating the login
Providers stored before 0.12.0
Before 0.12.0 the admin API and the importers stored any providerType. On upgrade to 0.13.0:
- a supported type stored in another case or with spaces (
OIDC,OAuth2,SAML) is rewritten tooidc,oauth2orsamlby a migration; GET /admin/upgrade/healthreports the rows the broker cannot sign in with in theidentity_provider_typeswarning, asrealm/alias (type, enabled|disabled):- Needs configuration review: a SAML provider without a valid SAML configuration. Every
samlrow stored before 0.13.0, when Idenplane had no SAML broker, has none: open it in the console and complete its SAML settings, or delete it.samlpandadfsrows (Auth0 exports) also need their type set tosaml. - Unsupported type: any type other than
oidc,oauth2andsaml. Change it to one the provider speaks, or delete it.
- Needs configuration review: a SAML provider without a valid SAML configuration. Every
An enabled provider in either list still shows a button on the login page that cannot complete a sign-in, so review these first. The check is a warning only and never blocks an upgrade.
Configuring one
curl -X POST http://localhost:3000/admin/realms/my-realm/identity-providers -H "x-admin-api-key: $ADMIN_API_KEY" -H "Content-Type: application/json" -d '{
"alias": "okta",
"displayName": "Okta",
"providerType": "oidc",
"clientId": "0oa...",
"clientSecret": "...",
"issuer": "https://your-org.okta.com",
"authorizationUrl": "https://your-org.okta.com/oauth2/v1/authorize",
"tokenUrl": "https://your-org.okta.com/oauth2/v1/token",
"userinfoUrl": "https://your-org.okta.com/oauth2/v1/userinfo",
"jwksUrl": "https://your-org.okta.com/oauth2/v1/keys",
"defaultScopes": "openid profile email",
"enabled": true
}'
alias identifies the provider within the realm and appears in its callback URL, so pick it once and keep it.
Options that change behaviour
| Field | Effect |
|---|---|
trustEmail | Accept the provider's email as verified, skipping your own verification step |
linkOnly | Allow linking to existing accounts but do not create new ones from this provider |
syncUserProfile | Refresh name and email from the provider on each login |
trustEmail makes the provider authoritative for email addresses. Only enable it for a provider that verifies them — otherwise someone can claim an address they do not own and, if an account already exists for it, be linked to that account.
Next Steps
Authorization Guide Learn about RBAC, permissions, and access control policies
MFA Setup Configure multi-factor authentication for your users
API Reference Complete REST API documentation with examples
React SDK Integrate Idenplane into your React application