Skip to content

Federating Keycloak with Microsoft Entra ID

This lab demonstrates setting up Keycloak as an Identity Provider (IDP) and federating it with Microsoft Entra ID for federated authentication.


Architecture Overview

┌─────────────────┐     Federation      ┌─────────────────┐
│                 │◄──────────────────►│                 │
│   Keycloak      │   SAML / OIDC       │   Entra ID      │
│   (Your IDP)    │                     │   (Microsoft)   │
│                 │                     │                 │
└────────┬────────┘                     └─────────────────┘

         │ Users authenticate

┌─────────────────┐
│   Your Apps     │
│   (SP/Client)   │
└─────────────────┘

Two Federation Scenarios:

  1. Entra as Identity Broker → Users sign in via Entra, Keycloak trusts Entra
  2. Keycloak as Identity Broker → Users sign in via Keycloak, which can redirect to Entra

Part 1: Deploy Keycloak on Render

Prerequisites

Step 1: Create PostgreSQL Database on Render

  1. Go to Render DashboardNewPostgreSQL
  2. Configure:
    • Name: keycloak-db
    • Database: keycloak
    • User: keycloak
    • Region: Choose closest
    • Plan: Free (for testing)
  3. Note the Internal Database URL after creation

Step 2: Deploy Keycloak Web Service

  1. NewWeb ServiceBuild from Git

  2. Connect your repo containing the Dockerfile

  3. Configure:

    SettingValue
    Namekeycloak
    RegionSame as database
    Branchmain
    Root Directoryazure/az-104/01-identity-governance/labs/08-federating-keyclock
    RuntimeDocker
    Instance TypeStarter ($7/mo) or Free
  4. Environment Variables:

    bash
    # Database connection (from your Render PostgreSQL)
    KC_DB_URL=jdbc:postgresql://<internal-hostname>:5432/keycloak
    KC_DB_USERNAME=keycloak
    KC_DB_PASSWORD=<your-db-password>
    
    # Admin credentials (CHANGE THESE!)
    KEYCLOAK_ADMIN=admin
    KEYCLOAK_ADMIN_PASSWORD=<strong-password>
    
    # Hostname (your Render URL)
    KC_HOSTNAME=keycloak-xxxx.onrender.com
  5. Click Create Web Service

Step 3: Verify Deployment

Once deployed, access:

  • Admin Console: https://keycloak-xxxx.onrender.com/admin
  • Health Check: https://keycloak-xxxx.onrender.com/health

Part 2: Configure Keycloak Realm

Create a New Realm

  1. Log into Keycloak Admin Console
  2. Click dropdown (top-left, shows "master") → Create Realm
  3. Realm name: azure-federation-lab
  4. Click Create

Create a Test Client (Your Application)

  1. ClientsCreate client

  2. Configure:

    SettingValue
    Client typeOpenID Connect
    Client IDtest-app
    NameTest Application
  3. Capability config:

    • Client authentication: ON
    • Authorization: OFF
    • Standard flow: ON (for web apps)
    • Direct access grants: ON (for testing)
  4. Login settings:

    • Valid redirect URIs: https://your-app.com/* or http://localhost:3000/*
    • Web origins: +
  5. Save and note the Client Secret from Credentials tab


Part 3: Federation Scenario A — Entra ID as Identity Provider in Keycloak

Users click "Sign in with Microsoft" in your Keycloak-protected app

Step 1: Register App in Entra ID

  1. Go to Entra Admin CenterApplicationsApp registrations

  2. New registration:

    SettingValue
    NameKeycloak Federation
    Supported account typesAccounts in this org directory only
    Redirect URIWeb: https://keycloak-xxxx.onrender.com/realms/azure-federation-lab/broker/microsoft/endpoint
  3. After creation, note:

    • Application (client) ID
    • Directory (tenant) ID
  4. Certificates & secretsNew client secret

    • Description: Keycloak
    • Expires: 24 months
    • Copy the Value immediately!
  5. API permissionsAdd permissionMicrosoft Graph:

    • openid
    • profile
    • email
    • User.Read

    Click Grant admin consent

Step 2: Add Microsoft as Identity Provider in Keycloak

  1. In Keycloak: Identity ProvidersAdd providerMicrosoft

  2. Configure:

    SettingValue
    Aliasmicrosoft
    Display NameSign in with Microsoft
    Client ID<Application ID from Entra>
    Client Secret<Secret Value from Entra>
    Default Scopesopenid profile email
  3. Advanced Settings:

    • Sync mode: import
    • Trust Email: ON
  4. Save

Step 3: Test the Federation

  1. Open: https://keycloak-xxxx.onrender.com/realms/azure-federation-lab/account
  2. Click Sign in with Microsoft
  3. Authenticate with your Entra credentials
  4. You should be redirected back to Keycloak, logged in!

Part 4: Federation Scenario B — Keycloak as External IDP for Entra (SAML)

Entra trusts Keycloak as an external identity provider

Step 1: Configure Keycloak SAML Metadata

  1. In Keycloak, access your realm's SAML metadata:

    https://keycloak-xxxx.onrender.com/realms/azure-federation-lab/protocol/saml/descriptor
  2. Download/save this XML—you'll need it for Entra

Step 2: Create Enterprise App in Entra with SAML SSO

  1. Entra Admin CenterEnterprise applicationsNew application

  2. Create your own application:

    • Name: Keycloak Federation
    • What are you looking to do: Integrate any other application you don't find in the gallery (Non-gallery)
  3. Single sign-onSAML

  4. Basic SAML Configuration:

    SettingValue
    Identifier (Entity ID)https://keycloak-xxxx.onrender.com/realms/azure-federation-lab
    Reply URL (ACS)https://keycloak-xxxx.onrender.com/realms/azure-federation-lab/broker/saml/endpoint
    Sign on URLhttps://keycloak-xxxx.onrender.com/realms/azure-federation-lab/protocol/saml
  5. User Attributes & Claims:

    • Map user.mailemail
    • Map user.displaynamename
  6. Download Federation Metadata XML from Entra

Step 3: Add Entra as SAML IDP in Keycloak

  1. Identity ProvidersAdd providerSAML v2.0

  2. Import from URL:

    https://login.microsoftonline.com/<tenant-id>/federationmetadata/2007-06/federationmetadata.xml
  3. Configure:

    SettingValue
    Aliasentra-saml
    Display NameMicrosoft Entra (SAML)
    Service Provider Entity IDhttps://keycloak-xxxx.onrender.com/realms/azure-federation-lab
  4. Save


Part 5: Workload Identity Federation (Advanced)

Use Keycloak-issued tokens to authenticate to Azure resources WITHOUT secrets!

The Concept

Instead of storing Azure service principal secrets in Keycloak, configure Azure to trust tokens issued by Keycloak:

┌─────────────────┐                        ┌─────────────────┐
│   Keycloak      │──Issues JWT Token───►│                 │
│   (Token        │                        │   Azure         │
│    Issuer)      │                        │   Resource      │
│                 │                        │   (trusts KC)   │
└─────────────────┘                        └─────────────────┘

Step 1: Create App Registration with Federated Credential

  1. Entra Admin CenterApp registrationsNew registration

    • Name: Keycloak-Workload-Identity
    • Account types: Single tenant
  2. Certificates & credentialsFederated credentialsAdd credential

  3. Configure:

    SettingValue
    Federated credential scenarioOther issuer
    Issuerhttps://keycloak-xxxx.onrender.com/realms/azure-federation-lab
    Subject identifier<client-id-of-your-keycloak-client>
    Namekeycloak-federation
    Audienceapi://AzureADTokenExchange
  4. Note the Application (client) ID and Tenant ID

Step 2: Assign Azure RBAC to the App

  1. Go to a resource (e.g., Storage Account)
  2. Access control (IAM)Add role assignment
  3. Role: Storage Blob Data Reader
  4. Members: Select the Keycloak-Workload-Identity app

Step 3: Exchange Keycloak Token for Azure Token

bash
# 1. Get token from Keycloak
KEYCLOAK_TOKEN=$(curl -s -X POST \
  "https://keycloak-xxxx.onrender.com/realms/azure-federation-lab/protocol/openid-connect/token" \
  -d "client_id=test-app" \
  -d "client_secret=<your-client-secret>" \
  -d "grant_type=client_credentials" \
  -d "scope=openid" | jq -r '.access_token')

# 2. Exchange for Azure token
AZURE_TOKEN=$(curl -s -X POST \
  "https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token" \
  -d "client_id=<keycloak-workload-identity-app-id>" \
  -d "scope=https://storage.azure.com/.default" \
  -d "client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer" \
  -d "client_assertion=$KEYCLOAK_TOKEN" \
  -d "grant_type=client_credentials" | jq -r '.access_token')

# 3. Use Azure token to access resources
curl -H "Authorization: Bearer $AZURE_TOKEN" \
  -H "x-ms-version: 2020-04-08" \
  "https://<storage-account>.blob.core.windows.net/<container>?restype=container&comp=list"

Troubleshooting

Common Issues

IssueSolution
Keycloak won't start on RenderCheck KC_DB_URL format, ensure PostgreSQL is running
"Invalid redirect URI"Ensure exact match including trailing slashes
SAML signature validation failedDownload fresh metadata, re-import
Token exchange failsVerify issuer URL matches exactly (no trailing slash)
"AADSTS50020" errorCheck tenant ID and audience configuration

Useful Debug URLs

PurposeURL
Keycloak OIDC Config/realms/{realm}/.well-known/openid-configuration
Keycloak SAML Metadata/realms/{realm}/protocol/saml/descriptor
Entra OIDC Confighttps://login.microsoftonline.com/{tenant}/v2.0/.well-known/openid-configuration
Entra SAML Metadatahttps://login.microsoftonline.com/{tenant}/federationmetadata/2007-06/federationmetadata.xml

Clean Up

  1. Render: Delete web service and database
  2. Entra: Delete app registrations created for this lab
  3. RBAC: Remove any role assignments

Further Reading

Released under the MIT License.