An Identity Broker is an intermediary service that connects service providers with identity providers (IdPs). It establishes trust with external identity providers and allows their identities to access internal services.

When acting as an identity broker, Keycloak enables:

  • Linking an existing account with one or more external identities
  • Creating a new account based on identity provider information
  • Centralized identity management across realms and domains

What Is an Identity Provider?

An identity provider (IdP) authenticates users and sends authentication/authorization data.

Examples include:

  • Social providers such as Facebook, Google, or Twitter
  • Business partner identity systems
  • Cloud-based identity services

Keycloak supports identity providers based on:

  • Security Assertion Markup Language (SAML v2.0)
  • OpenID Connect (OIDC v1.0)
  • OAuth 2.0 (OAuth v2.0)

Brokering Overview

When Keycloak acts as an identity broker:

  • Users are not forced to authenticate directly with Keycloak.
  • The login page displays available identity providers.
  • If a default identity provider is configured, users are automatically redirected to it.

Standard Identity Broker Flow

The general authentication sequence works as follows:

  1. An unauthenticated user requests a protected resource.
  2. The client application redirects the user to Keycloak.
  3. Keycloak displays a login page listing configured identity providers.
  4. The user selects an identity provider.
  5. Keycloak redirects the user to that provider with an authentication request.
  6. The user authenticates with the identity provider.
  7. The identity provider redirects back to Keycloak with an authentication response (typically containing a security token).
  8. Keycloak validates the response.
    • If the user does not exist → Keycloak creates/imports the user (identity federation).
    • If the user exists → Keycloak may prompt for account linking.
  9. Keycloak issues its own token to the client application.
  10. The client grants access to the protected resource.

Variations are possible:

  • The client may request a specific provider directly.
  • Additional steps (e.g., 2FA) may be required after provider login.
  • Extra information may be collected during the first login flow.

Importantly, external identity providers only need to trust Keycloak. They do not interact directly with client applications.

Default Identity Provider

Keycloak can automatically redirect users to a specific provider instead of displaying the login page.

To configure:

  1. Go to Authentication.
  2. Open the Browser flow.
  3. Configure the Identity Provider Redirector.
  4. Set the Default Identity Provider.

If the configured provider is not found, the standard login form appears.

This authenticator also processes the kc_idp_hint parameter, allowing clients to suggest a specific identity provider.

If additional steps (like 2FA) are required after external login, configure a Post Login Flow.

General Configuration of Identity Providers

Identity providers are configured per realm and are enabled for all applications by default.

To configure:

  1. Go to Identity Providers.

  1. Select an identity provider. Keycloak displays the configuration page for the identity provider you selected.

When you configure an identity provider, the identity provider appears on the Keycloak login page as an option. You can place custom icons on the login screen for each identity provider. See custom icons for more information.

Types of Identity Providers

Social Providers

Enable login via social accounts such as:

  • Google
  • Facebook
  • LinkedIn
  • Microsoft
  • GitHub
  • GitLab
  • PayPal
  • Stack Overflow

…and others.

Protocol-Based Providers

Allow integration with any provider compliant with:

  • Security Assertion Markup Language
  • OpenID Connect

This enables federation with enterprise or standards-based identity systems.

Common Configuration Options

All identity providers share core configuration fields:

Configuration Description
Alias
  • Unique identifier.
  • Used to build redirect URIs.
  • Required.
  • Examples: facebook, google, idp.acme.com
Enabled
  • Turns the provider ON or OFF.
Hide on Login Page
  • If ON, not shown on login page.
  • Still accessible via kc_idp_hint.
Account Linking Only
  • Only links accounts.
  • Cannot authenticate users.
  • Not shown on login page.
Store Tokens
  • Stores provider tokens in Keycloak.
Stored Tokens Readable
  • Allows retrieval of stored tokens.
  • Applies to broker client-level role “read token”.
Trust Email
  • If ON, email is trusted and marked verified.
  • Skips email verification if required.
  • For OIDC, respects email_verified claim.
  • Behavior depends on Sync Mode (especially FORCE).
GUI Order
  • Controls display order on login page.
Verify Essential Claim
  • Requires a specific JWT claim in ID token.
Essential Claim
  • Claim name to check (case-sensitive).
Essential Claim Value
  • Expected value (supports regex).
First Login Flow
  • Flow executed the first time a user logs in via this provider.
Post Login Flow
  • Flow executed after successful external login.
Sync Mode
  • Controls how user data is updated:
    • Legacy – Current behavior
    • Import – No updates after initial import
    • Force – Always update user data
Case-Sensitive Username
  • If enabled, keeps original case from provider.
  • Otherwise converts to lowercase.
  • Affects federated identity username only.
Show in Account Console
  • Controls visibility in user account console:
    • Always
    • When linked
    • Never

Social Identity Providers

A social identity provider allows authentication to be delegated to trusted social platforms. Keycloak supports multiple providers, including:

Google, Facebook, Twitter, GitHub, LinkedIn, Microsoft, Stack Overflow, Bitbucket, GitLab, Instagram, OpenShift 4, and PayPal.

Bitbucket

To configure login with Bitbucket:

  1. In Keycloak, go to Identity ProvidersAdd providerBitbucket.

  1. Copy the Redirect URI.
  2. In Bitbucket Cloud, create an OAuth consumer.
  3. Paste the Redirect URI into the Callback URL field.
  4. Enable Email and Read permissions under Account.
  5. Copy the generated Key and Secret.
  6. Paste them into Client ID and Client Secret in Keycloak.
  7. Click Add.

Facebook

To configure login with Facebook:

  1. Click Identity Providers in the menu.
  2. From the Add provider list, select Facebook.

  1. Copy the value of Redirect URI to your clipboard.
  2. In a separate browser tab, open the Meta for Developers.
    1. Click My Apps.
    2. Select Create App.

  1. Select Other.

  1. Select Consumer

  1. Fill in all required fields.
  2. Click Create app. Meta then brings you to the dashboard.

  1. Click Set Up in the Facebook Login box.
  2. Select Web.
  3. Enter the Redirect URI’s value into the Site URL field and click Save.
  4. In the navigation panel, select App settings – Basic.
  5. Click Show in the App Secret field.
  6. Note the App ID and the App Secret.
  1. Enter the App ID and App Secret values from your Facebook app into the Client ID and Client Secret fields in Keycloak.
  2. Click Add
  3. Enter the required scopes into the Default Scopes field. By default, Keycloak uses the email scope. See Graph API for more information about Facebook scopes.

Keycloak sends profile requests to graph.facebook.com/me?fields=id,name,email,first_name,last_name by default. The response contains the id, name, email, first_name, and last_name fields only. To fetch additional fields from the Facebook profile, add a corresponding scope and add the field name in the Additional user’s profile fields configuration option field.

GitHub

To configure login with GitHub:

  1. In Keycloak, select Identity ProvidersGithub.

  1. Copy the Redirect URI.
  2. Create either:
    • A GitHub App (supports token refresh), or
    • An OAuth App (no refresh support).
  3. Add the Redirect URI as the Authorization callback URL.
  4. Copy the Client ID and Client Secret.
  5. Paste them into Keycloak.
  6. Enable JSON Format (required for token refresh).
  7. Click Add.

GitLab

  1. In Keycloak, select Identity ProvidersGitLab.

  1. Copy the Redirect URI.
  2. Create a new GitLab application.
  3. Use the Redirect URI.
  4. Copy the Application ID and Secret.
  5. Paste into Keycloak as Client ID and Client Secret.
  6. Click Add.

Google

To configure login with Google:

  1. In Keycloak, select Identity ProvidersGoogle.

  1. Copy the Redirect URI.
  2. In Google Cloud Console:
    • Create an OAuth consent screen (User type: External).
    • Create OAuth Client ID (Web application).
    • Add Redirect URI to Authorized redirect URIs.
  3. Copy the Client ID and Client Secret.
  4. Paste into Keycloak.
  5. Click Add.
  6. Default scopes: openid profile email.
  7. (Optional) Restrict to a G Suite domain via Hosted Domain field.
  8. Click Save.

LinkedIn

  1. In Keycloak, select Identity ProvidersLinkedIn.

  1. Copy the Redirect URI.
  2. Create an app in the LinkedIn developer portal.
  3. Add Redirect URI under Auth tab.
  4. Request Sign In with LinkedIn (OpenID Connect) product.
  5. Copy Client ID and Client Secret into Keycloak.
  6. Click Add.

Microsoft

  1. In Keycloak, select Identity ProvidersMicrosoft.

  1. Copy the Redirect URI.
  2. Register an app in Azure (App registrations).
  3. Add Redirect URI under Web platform.
  4. Create a client secret under Certificates & secrets.
  5. Copy:
    • Application (client) ID
    • Secret Value
  6. Paste into Keycloak and click Add.

OpenShift 4

Prerequisites:

  • OpenShift certificate stored in Keycloak truststore.
  • Keycloak configured to use the truststore.

Steps:

  1. Run:
    oc cluster-info
  2. Locate the API URL (e.g., https://api.<domain>:6443).
  3. In Keycloak, select Identity ProvidersOpenshift v4.
  4. Enter:
    • Client ID
    • Client Secret
    • Base URL (OpenShift API URL)

  1. Register your client, either via OpenShift 4 Console (Home → API Explorer → OAuth Client → Instances) or using the oc command-line tool.
$ oc create -f <(echo '
kind: OAuthClient
apiVersion: oauth.openshift.io/v1
metadata:
 name: kc-client 
secret: "..." 
redirectURIs:
 - "<here you can paste the Redirect URI that you copied in the previous step>" 
grantMethod: prompt 
')
  1. Ensure redirect URI matches configuration.

In the end you should see the OpenShift 4 Identity Provider on the login page of your Keycloak instance. After clicking on it, you should be redirected to the OpenShift 4 login page.

PayPal

  1. In Keycloak, select Identity ProvidersPayPal.

  1. Copy the Redirect URI.
  2. Create a PayPal app in the developer portal.
  3. Enable Log in with PayPal.
  4. Set Return URL to Redirect URI (use 127.0.0.1 instead of localhost if local).
  5. Copy Client ID and Secret key 1.
  6. Paste into Keycloak and click Add.

Stack Overflow

  1. In Keycloak, select Identity ProvidersStack Overflow.

  1. Register application on Stack Apps.

  1. Provide:
    • Application Name
    • OAuth Domain

  1. Copy:
    • Client Id
    • Client Secret
    • Key
  2. Paste into Keycloak fields.
  3. Click Add.

Twitter

Prerequisite: Twitter Developer Account

  1. In Keycloak, select Identity ProvidersTwitter.

  1. Copy the Redirect URI.
  2. Create an app in Twitter Application Management.
  3. Configure:
    • Type: Web App
    • Callback URI = Redirect URI
    • Website URL (not localhost)
  4. Copy API Key and API Key Secret.
  5. Paste into Keycloak and click Add.

OpenID Connect v1.0 Identity Providers

Keycloak can broker identity providers that implement the OpenID Connect (OIDC) v1.0 protocol. These external IDPs must support the Authorization Code Flow to authenticate users and authorize access.

Adding an OpenID Connect v1.0 Provider

Procedure:

  1. In the Admin Console, click Identity Providers.
  2. From Add provider, select OpenID Connect v1.0.

  1. Enter the required configuration settings.

You can also import configuration automatically from an OpenID Provider Metadata document (for example:
<root>/realms/realm-name/.well-known/openid-configuration).

OpenID Connect Configuration Options

Below are the key configuration fields available when setting up an OIDC identity provider.

Endpoints

Configuration Description
Authorization URL The OIDC authorization endpoint.
Token URL The OIDC token endpoint.
Logout URL (optional) The OIDC logout endpoint.
User Info URL Endpoint providing user profile information.

Client Configuration

Configuration Description
Client ID The realm’s OIDC client identifier when acting as a client to the external IDP.
Client Secret Required for Authorization Code Flow (unless using JWT-based client authentication).
Client Authentication Defines the authentication method used with the IDP:
  • Client secret
  • JWT signed with private key (uses the realm private key)
  • Client secret as JWT
    • Refer to OIDC client authentication specifications for details.
Client Assertion Signature Algorithm Required when using JWT-based authentication.
  • Defaults:
    • RS256 for private key JWT
    • HS256 for client secret JWT
Client Assertion Audience Audience used in client assertions (default: IDP token endpoint URL).

Token and Scope Settings

Configuration Description
Default Scopes OIDC scopes sent with authentication request.
Default: openid
Multiple scopes must be space-separated.
Prompt Controls authentication behavior (e.g., force re-authentication).
Defined by the OIDC specification.
Accepts prompt=none forward from client Enables forwarding prompt=none requests to the IDP when:
  • A default IDP is configured, or
  • kc_idp_hint is used
Behavior:
  • If unauthenticated at IDP → login_required
  • If authenticated but interaction needed (e.g., required actions, consent) → interaction_required

State Handling

Configuration Description
Requires short state parameter Enable if the IDP does not support long state parameters (e.g., >100 characters).
This may slightly limit functionality in rare edge cases.

Signature Validation

Configuration Description
Validate Signatures When enabled, Keycloak verifies ID Token signatures from the IDP.
Public keys are cached for performance.
Use JWKS URL If enabled, Keycloak retrieves public keys from the IDP’s JWKS endpoint.
Automatically updates keys when the IDP rotates them.
JWKS URL URL pointing to IDP JWK keys.
Example (external Keycloak IDP):
http://<host>/realms/<realm>/protocol/openid-connect/certs
Validating Public Key (PEM format) Used when JWKS URL is disabled.
Validating Public Key ID Required when:
  • JWKS URL is disabled
  • IDP uses a specific key ID
    • Must match the IDP’s key ID.

Logout and Backchannel

Configuration Description
Backchannel Logout Sends a REST-based logout request to the IDP (no browser redirect).
Useful if the IDP does not rely solely on browser cookies.

Advanced Options

Configuration Description
Forwarded Query Parameters Comma-separated list of parameters to forward to the external Authorization Server.
Supports Client Assertions Enables provider-issued client assertions for client authentication.
Requires signature validation enabled.
Allows Client Assertions to be Re-used Permits reuse of client assertions if the client cannot generate new ones for each request.

Importing Configuration Automatically

You can import configuration via:

  • A URL to OpenID Provider Metadata
  • A local JSON file

If using another Keycloak instance as an external IDP, use:

<root>/realms/realm-name/.well-known/openid-configuration

This JSON document contains the provider’s metadata and endpoint definitions.

Using JWE (Encrypted Tokens)

If the provider issues JWE-encrypted ID Tokens or UserInfo responses:

  • The provider must know Keycloak’s public key.
  • Keycloak exposes a standard JWKS endpoint so the provider can retrieve encryption keys automatically.
  • The provider uses the realm’s configured encryption keys to encrypt tokens.

OAuth v2 Identity Providers

Keycloak can broker identity providers based on the OAuth 2.0 protocol. These providers must support the Authorization Code Flow to authenticate users and authorize access.

Adding an OAuth v2 Provider

Procedure:

  1. In the Admin Console, click Identity Providers.
  2. From Add provider, select OAuth v2.
  3. Configure the required settings.

OAuth v2 Configuration Settings

Endpoints

Configuration Description
Authorization URL The OAuth 2.0 authorization endpoint.
Token URL The OAuth 2.0 token endpoint.
User Info URL Endpoint used to retrieve user profile information.
Keycloak sends the access token as a Bearer token and expects a JSON response containing user claims such as ID, username, email, and names.

Client Configuration

Configuration Description
Client ID The identifier for the realm acting as a client to the external IDP.
Client Secret Required when using Authorization Code Flow (unless JWT-based authentication is used).
Client Authentication Defines how Keycloak authenticates to the provider:
  • Client secret
  • JWT signed with private key (uses realm private key)
  • Client secret as JWT
Client Assertion Signature Algorithm Required for JWT-based authentication.
Defaults:
  • RS256 for private key JWT
  • HS256 for client secret JWT
Client Assertion Audience Audience value for client assertions (default: token endpoint URL).

Scopes and Prompt

Configuration Description
Default Scopes Space-separated list of scopes sent in the authentication request.
Prompt Allows control over authentication behavior (for example, forcing re-authentication).
Accepts prompt=none forward from client Enables forwarding prompt=none requests to the default IDP (if configured or via kc_idp_hint).
Behavior:
  • If the user is unauthenticated at the IDP → login_required
  • If authenticated but interaction required (e.g., consent, required actions) → interaction_required

State Handling

Configuration Description
Requires short state parameter Enable if the IDP does not support long state values (e.g., more than 100 characters).
May slightly limit functionality in rare scenarios.

User Profile Retrieval

After successful authentication:

  1. The user is redirected back to Keycloak.
  2. Keycloak calls the User Info URL endpoint.
  3. The access token is sent as a Bearer token.
  4. The response must be a JSON document with user claims.

Even though OAuth 2.0 supports JWT access tokens, this broker assumes access tokens are opaque and retrieves user information from a separate endpoint.

Mapping User Profile Claims

You can configure how JSON claims are mapped to user attributes during federation.

User Profile Claims Configuration

Configuration Description
ID Claim Unique identifier for the user.
Default: sub
Username Claim Username attribute.
Default: preferred_username
Email Claim User’s email address.
Default: email
Name Claim Full name.
Default: name
Given Name Claim First name.
Default: given_name
Family Name Claim Last name.
Default: family_name

Importing Configuration Automatically

You can import configuration via:

  • A URL pointing to Authorization Server Metadata
  • A local metadata file

If connecting to an external Keycloak instance as an IDP, you can use:

<root>/realms/realm-name/.well-known/openid-configuration

This JSON document contains metadata describing the identity provider, including its endpoints and supported features.

SAML v2.0 Identity Providers

Keycloak can broker identity providers that use the SAML v2.0 protocol.

Adding a SAML v2.0 Identity Provider

Procedure:

  1. In the Admin Console, click Identity Providers.
  2. From Add provider, select SAML v2.0.

  1. Configure the required SAML settings.

You can also import configuration from a SAML entity descriptor (XML file or URL).

Core SAML Configuration

Entity Identifiers

Configuration Description
Service Provider Entity ID Identifies Keycloak (as Service Provider) to the external IDP.
Default: <root>/realms/realm-name
Identity Provider Entity ID Used to validate the Issuer in SAML assertions.
If empty, Issuer validation is skipped.

Endpoints

Configuration Description
Single Sign-On Service URL Endpoint that starts authentication.
Artifact Service URL SAML artifact resolution endpoint.
Single Logout Service URL Logout endpoint.
Backchannel Logout Enable if the IDP supports backchannel logout.

NameID and Principal Mapping

Configuration Description
NameID Policy Format Default:
urn:oasis:names:tc:SAML:2.0:nameid-format:persistent
Cannot use transient format with Subject NameID principal type.
Principal Type Determines how users are identified:
  • Subject NameID
  • SAML attribute (by Name or Friendly Name)
Principal Attribute Specifies the attribute name if Principal Type is attribute-based.
Allow Create Allows the IDP to create a new identifier for the principal.

Signing and Encryption

Configuration Description
Want AuthnRequests Signed If ON, Keycloak signs authentication requests using realm keys.
Want Assertions Signed Requires signed assertions from IDP.
Want Assertions Encrypted Requires encrypted assertions.
Signature Algorithm Used when signing AuthnRequests.
SHA1-based algorithms are deprecated and may not work with Java 17+ IDPs.
Encryption Algorithm Determines which encryption algorithm the IDP uses.
Matching decryption key must exist in realm keys (ENC usage).
SAML Signature Key Name Controls KeyName in signed documents:
  • KEY_ID
  • CERT_SUBJECT (required by some providers like Microsoft ADFS)
  • NONE

Authentication Behavior

Configuration Description
Force Authentication Forces credential entry even if user already has a session at IDP.
Validate Signature Requires signed SAML requests and responses.

Metadata and Certificates

Configuration Description
Metadata Descriptor URL URL where the IDP publishes its SAML metadata (IDPSSODescriptor).
Use Metadata Descriptor URL If ON:
  • Certificates are automatically downloaded and cached.
  • Keys refresh automatically depending on binding type and cache settings.
Validating X509 Certificates Used if Metadata Descriptor URL is OFF.
Multiple certificates can be provided (comma-separated).
Sign Service Provider Metadata Signs the SP metadata using realm key pair.

Subject Forwarding

Configuration Description
Pass Subject Enables forwarding of login_hint as Subject in SAML AuthnRequest.
If login_hint is empty, no subject is added.

Default login URL format:

http[s]://{host:port}/realms/realm-name/broker/broker-alias/login

Adding ?login_hint=value forwards the subject to the IDP.

Attribute Consuming Service

Configuration Description
Attribute Consuming Service Index Identifies which attribute set to request from IDP.
Attribute Consuming Service Name Descriptive name shown in SP metadata.

Mapped attributes are automatically included in generated SP metadata.

Importing Configuration

You can import SAML configuration by:

  • Uploading an XML entity descriptor
  • Providing a metadata URL

If connecting to another Keycloak instance as IDP, use:

<root>/realms/realm-name/protocol/saml/descriptor

This XML document contains the IDP’s metadata.

Requested AuthnContext Constraints

Clients can request specific authentication strength or methods (e.g., MFA, Kerberos).

You can define constraints under Requested AuthnContext Constraints.

Configuration Options

Configuration Description
Comparison How the IDP evaluates requirements:
  • Exact (default)
  • Minimum
  • Maximum
  • Better
AuthnContext ClassRefs Required authentication class references.
AuthnContext DeclRefs Required declaration references.

If no ClassRefs or DeclRefs are defined, no additional authentication constraints are enforced.

Service Provider (SP) Descriptor

Keycloak generates SAML SP metadata.

You can access it via:

http[s]://{host:port}/realms/realm-name/broker/broker-alias/endpoint/descriptor

Make sure configuration changes are saved before accessing the descriptor.

You can download this descriptor or import its URL into the external Identity Provider.

SPIFFE Identity Providers

Status: Preview (disabled by default)

Enable with:

--features=preview

or

-features=spiffe

Key Concepts

  • Each client must have a unique SPIFFE ID (subject identifier) per realm.
  • SPIFFE JWT SVIDs can be reused multiple times.
  • Security best practices:
    • Reduce token expiration time.
    • Ensure tokens cannot be intercepted in transit.

Adding a SPIFFE Provider

Procedure:

  1. Click Identity Providers.
  2. From* Add provider*, select SPIFFE.

  1. Configure the initial settings.

SPIFFE Settings

Configuration Description
Alias Used to link a client to this provider
SPIFFE Trust Domain Example: spiffe://my-trust-domain
SPIFFE Bundle Endpoint HTTPS URL for SPIFFE Bundle endpoint or OIDC JWKS endpoint exposing public keys

Kubernetes Identity Providers

A Kubernetes identity provider supports authenticating clients with Kubernetes service account tokens. It depends on the preview feature client-auth-federated.

The default issuer URL for a Kubernetes cluster is https://kubernetes.default.svc.cluster.local. You can discover this value by decoding a service account token to retrieve the value of the iss claim.

Keycloak must be able to invoke the endpoint <ISSUER>/.well-known/openid-configuration and additionally the JWKS endpoint returned in the well-known configuration. By default, these endpoints require authentication with a service account token. $Keycloak will automatically use the token from /var/run/secrets/kubernetes.io/serviceaccount/token if available and the token issuer matches the configured issuer.

Each identity provider must have a unique issuer. Each client must also have a unique subject identifier for each issuer. As the subject identifier is built from the namespace and service account name, each client must have its own service account if multiple clients share a namespace.

As a security best practice, do not use the default service account in a namespace, as it is shared with all Pods in a namespace. Instead, create an individual service account for each client.

Kubernetes service account tokens can be reused multiple times. As a security best practice, reduce the expiration time and make sure tokens can not be intercepted in communication between the client and Keycloak.

Procedure:

  1. Click Identity Providers in the menu.
  1. From the Add provider list, select Kubernetes.
  1. Enter your initial configuration options or proceed with the defaults.
Configuration Description
Alias The alias for the identity provider is used to link a client to the provider
Kubernetes Issuer URL The issuer URL of service account tokens. The URL <ISSUER>.well-known/openid-configuration must be available to Keycloak)
  1. When you create a new realm with the preview feature client-auth-federated enabled, the client authentication flow is already configured correctly. For existing realms, add to the client authentication flow the execution of Signed JWT – Federated as an alternative step. As built-in flows can not be updated, and if the default flow is your default, you will first need to duplicate the existing clients
  1. For each confidential OpenID Connect client that should authenticate via this provider:
    1. Change in the Credentials tab the Client Authenticator to Signed JWT – Federated.
    2. As Identity provider, enter the alias of the Kubernetes identity provider added in step 3.
    3. As Federated Subject, enter the subject identifier as issued by Kubernetes. This is usually system:serviceaccount:<namespace>:<serviceaccount>.
  1. For the Pod in Kubernetes add a service account:
    apiVersion: v1
    kind: Pod
    ...
    spec:
      serviceAccountName: <serviceaccount>
      ...
      volumes:
      - name: aud-token
        projected:
          defaultMode: 420
          sources:
          - serviceAccountToken:
              audience: https://example.com:8443/realms/test 
              expirationSeconds: 600 
              path: my-aud-token
    • Issuer URL of the Keycloak realm.
    • Maximum time allowed by Kubernetes and Keycloak is 3600 seconds

To verify your setup, assuming the client has a service account configured:

  1. In the Pod, retrieve the token
    cat /var/run/secrets/tokens/my-aud-token
  1. Use the token as the client credentials
    curl -k https://example.com:8443/realms/<realm>/protocol/openid-connect/token \
      -H 'Content-Type: application/x-www-form-urlencoded' \
      --data-urlencode grant_type=client_credentials \
      --data-urlencode client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
      --data-urlencode client_assertion=<token>
  1. Verify the response
    {
      "access_token": "ey...bw",
      "expires_in": 300,
      "refresh_expires_in": 0,
      "token_type": "Bearer",
      "not-before-policy": 0,
      "scope": "profile email"
    }

Client-suggested Identity Provider

OIDC applications can bypass the Keycloak login page by hinting at the identity provider they want to use. You can enable this by setting the kc_idp_hint query parameter in the Authorization Code Flow authorization endpoint.

With Keycloak OIDC client adapters, you can specify this query parameter when you access a secured resource in the application.

For example:

GET /myapplication.com?kc_idp_hint=facebook HTTP/1.1
Host: localhost:8080

In this case, your realm must have an identity provider with a facebook alias. If this provider does not exist, the login form is displayed.

If you are using the JavaScript adapter, you can also achieve the same behavior as follows:

const keycloak = new Keycloak({
        url: "http://keycloak-server",
        realm: "my-realm",
        clientId: "my-app"
);
await keycloak.createLoginUrl({
        idpHint: 'facebook'
});

With the kc_idp_hint query parameter, the client can override the default identity provider if you configure one for the Identity Provider Redirector authenticator. The client can disable the automatic redirecting by setting the kc_idp_hint query parameter to an empty value.

Mapping claims and assertions

You can import the SAML and OpenID Connect metadata, provided by the external IDP you are authenticating with, into the realm. After importing, you can extract user profile metadata and other information, so you can make it available to your applications.

Each user logging into your realm using an external identity provider has an entry in the local Keycloak database, based on the metadata from the SAML or OIDC assertions and claims.

Procedure:

  1. Click Identity Providers in the menu.
  1. Select one of the identity providers in the list.
  1. Click the Mappers tab.

  1. Click Add mapper.

  1. Select a value for Sync Mode Override. The mapper updates user information when users log in repeatedly according to this setting.
    1. Select legacy to use the behavior of the previous Keycloak version.
    2. Select import to import data from when the user was first created in Keycloak during the first login to Keycloak with a particular identity provider.
    3. Select force to update user data at each user login.
    4. Select inherit to use the sync mode configured in the identity provider. All other options will override this sync mode.
  1. Select a mapper from the Mapper Type list. Hover over the Mapper Type for a description of the mapper and configuration to enter for the mapper.
  1. Click Save.

For JSON-based claims, you can use dot notation for nesting and square brackets to access array fields by index. For example, contact.address[0].country.

To investigate the structure of user profile JSON data provided by social providers, you can enable the DEBUG level logger org.keycloak.social.user_profile_dump when starting the server.

Available user session data

After a user login from an external IDP, Keycloak stores user session note data that you can access. This data can be propagated to the client requesting log in using the token or SAML assertion passed back to the client using an appropriate client mapper.

identity_provider
The IDP alias of the broker used to perform the login.

identity_provider_identity
The IDP username of the currently authenticated user. Often, but not always, the same as the Keycloak username. For example, Keycloak can link a user john` to a Facebook user john123@gmail.com. In that case, the value of the user session note is john123@gmail.com.

You can use a Protocol Mapper of type User Session Note to propagate this information to your clients.

First login flow

When users log in through identity brokering, Keycloak imports and links aspects of the user within the realm’s local database. When Keycloak successfully authenticates users through an external identity provider, two situations can exist:

  • Keycloak has already imported and linked a user account with the authenticated identity provider account. In this case, Keycloak authenticates as the existing user and redirects back to the application.
  • No account exists for this user in Keycloak. Usually, you register and import a new account into the Keycloak database, but there may be an existing Keycloak account with the same email address. Automatically linking the existing local account to the external identity provider is a potential security hole. You cannot always trust the information you get from the external identity provider.

Different organizations have different requirements when dealing with some of these situations. With Keycloak, you can use the First Login Flow option in the IDP settings to choose a workflow for a user logging in from an external IDP for the first time. By default, the First Login Flow option points to the first broker login flow, but you can use your flow or different flows for different identity providers.

The flow is in the Admin Console under the Authentication tab. When you choose the First Broker Login flow, you see the authenticators used by default. You can re-configure the existing flow. For example, you can disable some authenticators, mark some of them as required, or configure some authenticators.

You can also create a new authentication flow, write your own Authenticator implementations, and use it in your flow. See Server Developer Guide for more information.

Default first login flow authenticators

Review Profile

  • This authenticator displays the profile information page, so the users can review their profile that Keycloak retrieves from an identity provider.
  • You can set the Update Profile On First Login option in the Actions menu.
  • When ON, users are presented with the profile page requesting additional information to federate the user’s identities.
  • When missing, users are presented with the profile page if the identity provider does not provide mandatory information, such as email, first name, or last name.
  • When OFF, the profile page does not display unless the user clicks in a later phase on the Review profile info link in the page displayed by the Confirm Link Existing Account authenticator.

Create User If Unique

This authenticator checks if there is already an existing Keycloak account with the same email or username like the account from the identity provider. If it’s not, then the authenticator just creates a new local Keycloak account and links it with the identity provider and the whole flow is finished. Otherwise it goes to the next Handle Existing Account subflow. If you always want to ensure that there is no duplicated account, you can mark this authenticator as REQUIRED. In this case, the user will see the error page if there is an existing Keycloak account and the user will need to link the identity provider account through Account management.

  • This authenticator verifies that there is already a Keycloak account with the same email or username as the identity provider’s account.
  • If an account does not exist, the authenticator creates a local Keycloak account, links this account with the identity provider, and terminates the flow.
  • If an account exists, the authenticator implements the next Handle Existing Account sub-flow.
  • To ensure there is no duplicated account, you can mark this authenticator as REQUIRED. The user sees the error page if a Keycloak account exists, and users must link their identity provider account through Account management.

Confirm Link Existing Account

  • On the information page, users see a Keycloak account with the same email. Users can review their profile again and use a different email or username. The flow restarts and goes back to the Review Profile authenticator.
  • Alternatively, users can confirm that they want to link their identity provider account with their existing Keycloak account.
  • Disable this authenticator if you do not want users to see this confirmation page and go straight to linking identity provider account by email verification or re-authentication.

Verify Existing Account By Email

  • This authenticator is ALTERNATIVE by default. Keycloak uses this authenticator if the realm has an SMTP setup configured.
  • The authenticator sends an email to users to confirm that they want to link the identity provider with their Keycloak account.
  • Disable this authenticator if you do not want to confirm linking by email, but want users to reauthenticate with their password.

Verify Existing Account By Re-authentication

  • Use this authenticator if the email authenticator is not available. For example, you have not configured SMTP for your realm. This authenticator displays a login screen for users to authenticate to link their Keycloak account with the Identity Provider.
  • Users can also re-authenticate with another identity provider already linked to their Keycloak account.
  • You can force users to use OTP. Otherwise, it is optional and used if you have set OTP for the user account.

Automatically link existing first login flow

To configure a first login flow that links users automatically without prompting, create a new flow with the following two authenticators:

Create User If Unique

This authenticator ensures Keycloak handles unique users. Set the authenticator requirement to Alternative.

Automatically Set Existing User

This authenticator sets an existing user to the authentication context without verification. Set the authenticator requirement to “Alternative”.

Disabling automatic user creation

The Default first login flow looks up the Keycloak account matching the external identity and offers to link them. If no matching Keycloak account exists, the flow automatically creates one.

This default behavior may be unsuitable for some setups. One example is when you use a read-only LDAP user store, where all users are pre-created. In this case, you must switch off automatic user creation.

To disable user creation:

Procedure:

  1. Click Authentication in the menu.
  1. Select First Broker Login from the list.
  1. Set Create User If Unique to DISABLED.
  1. Set Confirm Link Existing Account to DISABLED.

This configuration also implies that Keycloak itself won’t be able to determine which internal account would correspond to the external identity. Therefore, the Verify Existing Account By Re-authentication authenticator will ask the user to provide both username and password.

Detect existing user first login flow

In order to configure a first login flow in which:

  • only users already registered in this realm can log in,
  • users are automatically linked without being prompted,

create a new flow with the following two authenticators:

Detect Existing Broker User

This authenticator ensures that unique users are handled. Set the authenticator requirement to REQUIRED.

Automatically Set Existing User

Automatically sets an existing user to the authentication context without any verification. Set the authenticator requirement to REQUIRED.

You have to set the First Login Flow of the identity provider configuration to that flow. You could set the also set Sync Mode to force if you want to update the user profile (Last Name, First Name…​) with the identity provider attributes.

With this configuration, Keycloak is unable to determine which internal account corresponds to the external identity. The Verify Existing Account By Re-authentication authenticator asks the provider for the username and password.

Override existing broker link

When an another account needs to be linked to the same Keycloak account within the same identity provider, you can configure the following authenticator.

Confirm Override Existing Link

This authenticator will detect the existing broker link for the user and display a confirmation page to confirm overriding the existing broker link. Set the authenticator requirement to REQUIRED.

A typical use of this authenticator is a scenario such as the following:

  • For example, consider a Keycloak user john with the email john@gmail.com. That user is linked to the identity provider google with the google username john@gmail.com .
  • Then for instance Keycloak user john creates new Google account with email john-new@gmail.com
  • Then during login to Keycloak, the user authenticated to the identity provider google with a new username such as john-new@gmail.com, which is not linked to any Keycloak account yet (as Keycloak account john is still linked with the google user john@gmail.com) and hence the first-broker-login flow is triggered.
  • During first-broker-login, the Keycloak user john is authenticated somehow (either by default first-broker-login re-authentication or for instance by authenticator like Detect existing broker user)
  • Now with this authenticator in the authentication flow, it is possible to override the IDP link to the google identity provider of Keycloak user john with the new google link to google user john-new@gmail.com after user john confirms this.

When creating authentication flows with this authenticator, make sure to add this authenticator once other authenticators that are already established the Keycloak user by other means (either by re-authentication or after Detect existing broker user as mentioned above.

Post login flow

Post login flow is useful for the situations when you want to trigger some additional authentication actions after every login with the particular identity provider. For example, you may want to trigger 2-factor authentication after every login of Keycloak to Facebook because Facebook does not provide 2-factor authentication during its login.

Once you setup the authentication flow with the needed steps, set it as Post login flow when configuring the identity provider.

Post login flow examples

Requesting 2-factor authentication after identity provider login

The easiest way is to enforce authentication with one particular 2-factor method. For example, when requesting OTP, the flow can look like this with only a single authenticator configured. This type of flow asks the user to configure the OTP during the first login with the identity provide when the user does not have OTP set on the account.

The more complex setup can include multiple 2-factor authentication methods configured as ALTERNATIVE. In this case, make sure that the user is requested to setup one of the methods if that user does not yet have any 2-factor authentication configured on the account. This could be done as follows:

  • Make sure that one of the 2-factor methods is configured as REQUIRED in the First login flow. This method can works if you expect all your users to be registered by the identity provider login.
  • Wrap the 2-factor methods as ALTERNATIVE into a conditional subflow such as one called 2FA and create another conditional subflow such as one called OTP if no 2FA, which will be triggered only if the previous subflow was not executed and will ask user to add one of the 2-factor methods (for example, OTP). The example of a similar flow configuration is provided in the Conditions section of the Authentication flows chapter.

Requesting additional authentication steps for the dedicated clients

In some cases, a client or group of clients may need to perform some additional steps after identity provider login. The following is an example of a flow that prescribes that when the client scope foo is requested, the user is required to authenticate with the OTP after identity provider login.

This is an example of configuring the Condition - client scope for requesting the specified client scope.

The requested clients need to have this client scope set on them either as default or as optional. In the latter case, the flow is executed only if the client scope is requested by the client (for example, by the scope parameter in the case of OIDC/OAuth2 client logins).

Retrieving external IDP tokens

With Keycloak, you can store tokens and responses from the authentication process with the external IDP using the Store Token configuration option on the IDP’s settings page.

Application code can retrieve these tokens and responses to import extra user information or to request the external IDP securely. For example, an application can use the Google token to use other Google services and REST APIs. To retrieve a token for a particular identity provider, send a request as follows:

GET /realms/realm-name/broker/{provider_alias}/token HTTP/1.1
Host: localhost:8080
Authorization: Bearer <KEYCLOAK ACCESS TOKEN>

An application must authenticate with Keycloak and receive an access token. This access token must have the broker client-level role read-token set, so the user must have a role mapping for this role, and the client application must have that role within its scope. In this case, since you are accessing a protected service in Keycloak, send the access token issued by Keycloak during the user authentication. You can assign this role to newly imported users in the broker configuration page by setting the Stored Tokens Readable switch to ON.

These external tokens can be re-established by logging in again through the provider or using the client-initiated account linking API.

Identity broker logout

When logging out, Keycloak sends a request to the external identity provider that is used to log in initially and logs the user out of this identity provider.

Haben Sie noch weitere Fragen?
Visit the Support Portal

Thanks for your feedback.