📑 Table of Contents

🎯 Lab Overview & What You Will Build

In this intermediate lab, you will implement a complete enterprise Single Sign-On (SSO) infrastructure using SAML 2.0 protocol and Keycloak Identity Provider. Building upon the LDAP directory you created in Lab 1, you will deploy Keycloak as your Identity Provider (IdP), federate it with your OpenLDAP directory to import users automatically, configure SAML 2.0 authentication for a sample web application, and test the complete SSO flow from user login to authenticated session. By the end of this lab, you will have a fully functional SSO system where users can authenticate once against Keycloak using their LDAP credentials and gain access to multiple applications—the exact same federated identity architecture used by enterprises to enable seamless access to SaaS applications like Salesforce, ServiceNow, AWS Console, and thousands of others.

What You Will Build

Learning Objectives

🌍 Real-World Scenario & Skills Application

🏢 Enterprise Scenario: GlobalTech SaaS Integration Project

You're an IAM Engineer at GlobalTech Corporation, a company with 5,000 employees that recently acquired three SaaS applications: Salesforce for CRM, ServiceNow for IT service management, and Workday for HR. Currently, employees must remember separate credentials for each system, leading to password fatigue, increased helpdesk tickets, and security risks from password reuse.

Your manager assigns you to implement SSO: "We need employees to log in once with their corporate credentials and access all three applications. The board wants this done in 60 days."

This lab teaches you exactly how to accomplish this. The skills you develop directly translate to:

  • SaaS Integration: Configuring SAML SSO for Salesforce, ServiceNow, Workday, Box, Slack, and thousands of enterprise applications
  • Identity Federation: Connecting cloud applications to your on-premises Active Directory or LDAP
  • Security Compliance: Meeting SOC 2, ISO 27001, and HIPAA requirements for centralized access control
  • User Experience: Eliminating password fatigue and reducing helpdesk tickets by 40-60%
  • Incident Response: Single point to disable access across all applications when employees leave

🎯 Skills You Will Gain & How They Apply

SAML Protocol Mastery

Understand assertions, bindings, and metadata. Essential for integrating any enterprise SaaS application.

Identity Provider Administration

Configure Keycloak/Okta/Azure AD. Core skill for any IAM engineer role.

User Federation

Connect IdPs to LDAP/AD. Required for hybrid cloud identity architectures.

Attribute Mapping

Map identity attributes between systems. Critical for provisioning and authorization.

SSO Troubleshooting

Debug SAML flows and decode assertions. The #1 skill for IAM support escalations.

Security Analysis

Validate signatures, certificates, and bindings. Essential for security assessments.

📋 Prerequisites & Requirements

⚠️ Required: Complete Lab 1 First

This lab builds directly on Lab 1: LDAP Fundamentals. You must have a working OpenLDAP server with users before proceeding. If you haven't completed Lab 1, do so now—it takes approximately 3-4 hours.

Environment Requirements

Component Requirement Purpose
Lab 1 Completion OpenLDAP running with 3 users User source for federation
VM RAM 6 GB minimum (8 GB recommended) Keycloak requires ~1.5 GB additional
VM Disk Space 10 GB free Keycloak image + data
Docker Version 24.0+ Container runtime
Web Browser Chrome, Firefox, or Edge Keycloak admin console & testing

Hypervisor Options

If you need to set up a new VM for this lab, you can use either:

Refer to Lab 1 for detailed hypervisor and Ubuntu VM installation instructions.

Knowledge Prerequisites

🏗️ Lab Architecture Blueprint

This diagram shows the complete SSO infrastructure you will build. The SAML authentication flow is highlighted at the bottom.

▼ SSO INFRASTRUCTURE STACK ▼

Layer 1: Physical Host Machine
Windows / macOS / Linux with VirtualBox or VMware
Layer 2: Hypervisor
VirtualBox 7.0+ │ VMware Workstation 17+
Layer 3: Ubuntu Virtual Machine
Ubuntu 22.04 LTS │ 6-8 GB RAM │ identitybytes-lab
Layer 4: Docker Engine
Docker CE 24.0+ │ Docker Compose │ sso-network (bridge)
Layer 5: Identity Services
🔐 KEYCLOAK IdP

Port 8080
Identity Provider
SAML 2.0 / OIDC

📁 OPENLDAP

Port 389
User Directory
dc=identitybytes,dc=lab

🌐 TEST APP (SP)

Port 8000
Service Provider
SAML Consumer

SAML 2.0 AUTHENTICATION FLOW
👤 User ──────► 🌐 Service Provider (App) ──────► 🔐 Keycloak IdP │ │ │ │ 1. Access Request 2. SAML AuthnRequest │ │ │ │ │ 3. User Login Form │ ◄─────────────────────────────────────────────────────────────┘ │ │ │ 4. Enter Credentials │ │ ─────────────────────────────────────────────────────────────► │ │ │ 5. SAML Response (Assertion) │ ◄─────────────────────────────────────────────────────────────┘ │ │ 👤 User ◄────── 6. Authenticated Session ◄────── Validate & Create Session

Component Interaction Summary

Component Role SAML Function
Keycloak Identity Provider (IdP) Issues SAML Assertions after authenticating users
OpenLDAP User Directory Stores user credentials; federated into Keycloak
Test Application Service Provider (SP) Consumes SAML Assertions to create user sessions
Web Browser User Agent Carries SAML messages between SP and IdP

🏷️ Environment Setup

Device Badges Legend

Code blocks in this lab are tagged with badges indicating where to run commands:

Ubuntu VM Commands to run in Ubuntu VM terminal
Web Browser Actions to perform in your web browser
Keycloak Console Configuration steps in Keycloak admin UI

Verify Lab 1 Environment

1

Confirm OpenLDAP is Running

Before proceeding, verify that your OpenLDAP container from Lab 1 is running and accessible. Navigate to your Lab 1 docker directory and check the container status. If the container is not running, start it using Docker Compose.

Ubuntu VM
cd ~/identity-bytes-labs/lab-01-ldap/docker docker compose ps # If not running, start it: docker compose up -d # Verify LDAP connectivity ldapsearch -x -H ldap://localhost -b "dc=identitybytes,dc=lab" -LLL "(objectClass=inetOrgPerson)" uid cn

Expected output: You should see your three users (jdoe, jsmith, bjohnson) listed. If you see "Can't contact LDAP server", start the container first.

2

Create Lab 2 Directory Structure

Create a dedicated directory for Lab 2 files. This keeps your lab environments organized and makes cleanup easier. You'll create subdirectories for Docker configurations and application files.

Ubuntu VM
mkdir -p ~/identity-bytes-labs/lab-02-saml-sso/{docker,app,config} cd ~/identity-bytes-labs/lab-02-saml-sso tree -L 2 .
3

Get OpenLDAP Container IP Address

Keycloak will need to connect to OpenLDAP. Since both run in Docker, we need to either use Docker networking or get the container's IP address. We'll use Docker's internal DNS for container-to-container communication.

Ubuntu VM
# Get the LDAP container's IP address docker inspect identitybytes-ldap --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' # Note this IP address - you'll need it for Keycloak configuration # Example output: 172.18.0.2

💡 Docker Networking Note

We'll create a shared Docker network so Keycloak can reach OpenLDAP by container name instead of IP address. This is more reliable as IPs can change on container restart.

🔐 Keycloak Deployment

4

Create Docker Network for SSO Services

Create a shared Docker network that will allow Keycloak and OpenLDAP containers to communicate using container names as hostnames. Then connect the existing LDAP container to this network.

Ubuntu VM
# Create shared network for SSO services docker network create sso-network # Connect existing LDAP container to the new network docker network connect sso-network identitybytes-ldap # Verify LDAP is connected docker network inspect sso-network --format '{{range .Containers}}{{.Name}} {{end}}'
5

Create Keycloak Docker Compose Configuration

Create a Docker Compose file for Keycloak. We'll use Keycloak 23.x (latest stable) with PostgreSQL as the database backend for better performance and persistence. The configuration includes development mode settings suitable for lab environments.

Ubuntu VM
cd ~/identity-bytes-labs/lab-02-saml-sso/docker cat <<'EOF' > docker-compose.yml version: '3.8' services: postgres: image: postgres:15-alpine container_name: keycloak-postgres environment: POSTGRES_DB: keycloak POSTGRES_USER: keycloak POSTGRES_PASSWORD: KeycloakDBP@ss123 volumes: - postgres_data:/var/lib/postgresql/data networks: - sso-network restart: unless-stopped keycloak: image: quay.io/keycloak/keycloak:23.0 container_name: keycloak-idp environment: KC_DB: postgres KC_DB_URL: jdbc:postgresql://postgres:5432/keycloak KC_DB_USERNAME: keycloak KC_DB_PASSWORD: KeycloakDBP@ss123 KEYCLOAK_ADMIN: admin KEYCLOAK_ADMIN_PASSWORD: AdminP@ss123! KC_HOSTNAME_STRICT: "false" KC_HTTP_ENABLED: "true" KC_PROXY: edge command: start-dev ports: - "8080:8080" depends_on: - postgres networks: - sso-network restart: unless-stopped volumes: postgres_data: networks: sso-network: external: true EOF cat docker-compose.yml
6

Start Keycloak Services

Launch Keycloak and its PostgreSQL database. The first startup takes 2-3 minutes as Keycloak initializes its database schema and imports default configurations. Monitor the logs to confirm successful startup.

Ubuntu VM
# Pull images and start services docker compose pull docker compose up -d # Wait for Keycloak to start (takes 1-2 minutes) echo "Waiting for Keycloak to start..." sleep 60 # Check container status docker compose ps # View Keycloak logs (look for "Keycloak started") docker compose logs keycloak | tail -20

Success indicator: Look for the message "Running the server in development mode" or "Keycloak 23.0 started" in the logs.

7

Access Keycloak Admin Console

Open your web browser and navigate to the Keycloak admin console. You'll log in with the admin credentials specified in the Docker Compose file. The admin console is where you'll configure realms, users, and SAML settings.

Web Browser
# Open in your browser: http://localhost:8080 # Click "Administration Console" # Login with: # Username: admin # Password: AdminP@ss123!

✅ Checkpoint

You should now see the Keycloak Admin Console dashboard showing the "master" realm. The master realm is Keycloak's administrative realm—we'll create a separate realm for our application users.

8

Create Identity Bytes Realm

In Keycloak, a Realm is a space where you manage users, credentials, roles, and groups. Think of it as a tenant or namespace. We'll create a dedicated realm called "identitybytes" for our SSO configuration. This separates our lab users from the Keycloak admin users in the master realm.

Keycloak Console
# GUI Steps in Keycloak Admin Console: 1. Click the dropdown "master" in the top-left corner 2. Click "Create Realm" 3. Enter the following: - Realm name: identitybytes - Enabled: ON 4. Click "Create" # You should now see "identitybytes" in the realm dropdown # All subsequent configuration will be in this realm

📁 LDAP User Federation

User Federation allows Keycloak to import users from external identity stores like LDAP or Active Directory. Instead of duplicating user accounts, Keycloak authenticates against the federated directory and caches user information locally.

9

Configure LDAP Provider

Navigate to User Federation in the Keycloak console and add an LDAP provider. This configuration tells Keycloak how to connect to your OpenLDAP server, where to find users, and how to authenticate them. We'll use the read-only account for browsing and the admin account for user import operations.

Keycloak Console
# GUI Steps in Keycloak Admin Console: 1. Ensure you're in the "identitybytes" realm (check top-left dropdown) 2. Left menu: Click "User federation" 3. Click "Add Ldap providers" # Fill in the following settings: ## General Options - UI display name: OpenLDAP - Vendor: Other ## Connection and Authentication Settings - Connection URL: ldap://identitybytes-ldap:389 (Use container name since both are on sso-network) - Enable StartTLS: OFF - Bind type: simple - Bind DN: cn=admin,dc=identitybytes,dc=lab - Bind credentials: SecureLabP@ss123! ## Click "Test connection" - should show "Successfully connected to LDAP" ## Click "Test authentication" - should show "Successfully authenticated to LDAP" ## LDAP Searching and Updating - Edit mode: READ_ONLY - Users DN: ou=people,dc=identitybytes,dc=lab - Username LDAP attribute: uid - RDN LDAP attribute: uid - UUID LDAP attribute: entryUUID - User object classes: inetOrgPerson ## Synchronization Settings - Import users: ON - Sync Registrations: OFF - Periodic Full Sync: ON - Full sync period: 3600 4. Click "Save"
10

Configure LDAP Attribute Mappers

Attribute mappers define how LDAP attributes are translated to Keycloak user attributes. The default mappers handle common attributes, but we'll verify they're correctly configured for our OpenLDAP schema. Navigate to the Mappers tab within your LDAP federation configuration.

Keycloak Console
# GUI Steps in Keycloak Admin Console: 1. In User Federation > OpenLDAP, click the "Mappers" tab 2. Verify these mappers exist (created by default): - username (uid → username) - first name (givenName → firstName) - last name (sn → lastName) - email (mail → email) # Add a mapper for job title: 3. Click "Add mapper" 4. Configure: - Name: title - Mapper type: user-attribute-ldap-mapper - User Model Attribute: title - LDAP Attribute: title - Read Only: ON 5. Click "Save"
11

Synchronize LDAP Users

Trigger a full synchronization to import all users from OpenLDAP into Keycloak. After sync completes, verify the users appear in Keycloak's user list. Each user will be marked as federated, indicating their source is the LDAP directory.

Keycloak Console
# GUI Steps in Keycloak Admin Console: 1. In User Federation > OpenLDAP, click the "Action" dropdown 2. Select "Sync all users" 3. Wait for sync to complete (shows "Success" message) # Verify users were imported: 4. Left menu: Click "Users" 5. Click "View all users" 6. You should see: - jdoe (John Doe) - jsmith (Jane Smith) - bjohnson (Bob Johnson) # Click on any user to see their attributes # Note the "Federation Link" showing they're from LDAP

✅ Checkpoint: User Federation Complete

You should now see 3 users in Keycloak's user list, all showing "OpenLDAP" as their federation link. These users can now authenticate to Keycloak using their LDAP passwords (SecureP@ss2024!).

🌐 SAML Application Configuration

Now we'll configure a SAML Service Provider (SP) in Keycloak. In production, this would be your enterprise application (Salesforce, ServiceNow, etc.). For this lab, we'll create a test configuration and use a SAML testing tool to simulate the SP.

12

Create SAML Client in Keycloak

A "Client" in Keycloak represents an application that can request authentication. We'll create a SAML 2.0 client that represents our Service Provider. The client configuration includes the SP's entity ID, assertion consumer service URL, and attribute mappings.

Keycloak Console
# GUI Steps in Keycloak Admin Console: 1. Ensure you're in the "identitybytes" realm 2. Left menu: Click "Clients" 3. Click "Create client" ## General Settings - Client type: SAML - Client ID: urn:identitybytes:saml:testapp (This is the SP Entity ID) - Name: Test SAML Application - Description: Lab 2 SAML test application - Click "Next" ## Login Settings - Root URL: http://localhost:8000 - Home URL: http://localhost:8000 - Valid redirect URIs: http://localhost:8000/* - Click "Next" ## SAML Capabilities (keep defaults) - Click "Save"
13

Configure SAML Client Settings

After creating the client, configure the advanced SAML settings. These include signature requirements, assertion encryption options, and the Assertion Consumer Service (ACS) URL where Keycloak sends SAML responses.

Keycloak Console
# GUI Steps in Keycloak Admin Console: 1. Click on your newly created client "urn:identitybytes:saml:testapp" 2. Go to "Settings" tab ## Configure these settings: ### Login Settings - Valid post logout redirect URIs: http://localhost:8000/* - Master SAML Processing URL: http://localhost:8000/saml/acs ### SAML Capabilities - Name ID Format: username - Force Name ID Format: ON - Force POST Binding: ON - Include AuthnStatement: ON ### Signature and Encryption - Sign Documents: ON - Sign Assertions: ON - Signature Algorithm: RSA_SHA256 - SAML Signature Key Name: KEY_ID - Canonicalization Method: EXCLUSIVE 3. Click "Save"
14

Configure Client Scopes and Attribute Mappers

Configure which user attributes are included in the SAML assertion. The Service Provider may need attributes like email, first name, last name, and groups to provision user accounts or make authorization decisions. We'll create mappers to include these in the SAML response.

Keycloak Console
# GUI Steps in Keycloak Admin Console: 1. In your SAML client, go to "Client scopes" tab 2. Click "urn:identitybytes:saml:testapp-dedicated" 3. Click "Add mapper" > "By configuration" 4. Select "User Attribute" ## Create Email Mapper: - Name: email - User Attribute: email - Friendly Name: email - SAML Attribute Name: email - SAML Attribute NameFormat: Basic - Click "Save" ## Create First Name Mapper: 5. Click "Add mapper" > "By configuration" > "User Attribute" - Name: firstName - User Attribute: firstName - Friendly Name: firstName - SAML Attribute Name: firstName - SAML Attribute NameFormat: Basic - Click "Save" ## Create Last Name Mapper: 6. Click "Add mapper" > "By configuration" > "User Attribute" - Name: lastName - User Attribute: lastName - Friendly Name: lastName - SAML Attribute Name: lastName - SAML Attribute NameFormat: Basic - Click "Save"
15

Download SAML Metadata

SAML metadata is an XML document that describes the IdP's endpoints, certificates, and capabilities. Service Providers use this metadata to configure trust with the IdP. Download both the IdP metadata and the realm's signing certificate.

Keycloak Console
# Download IdP Metadata via URL: # In browser, navigate to: http://localhost:8080/realms/identitybytes/protocol/saml/descriptor # Save this XML file as: idp-metadata.xml # Key information in metadata: # - entityID: URL identifying this IdP # - SingleSignOnService: Where to send SAML AuthnRequests # - X509Certificate: IdP's signing certificate
Ubuntu VM
# Download metadata via curl cd ~/identity-bytes-labs/lab-02-saml-sso/config curl -o idp-metadata.xml \ "http://localhost:8080/realms/identitybytes/protocol/saml/descriptor" # View the metadata cat idp-metadata.xml

✅ Testing SSO Flow

16

Deploy SAML Test Application

Deploy a simple Python Flask application that acts as a SAML Service Provider. This application will initiate SAML authentication with Keycloak and display the received SAML assertion. This simulates how a real application would integrate with your SSO system.

Ubuntu VM
cd ~/identity-bytes-labs/lab-02-saml-sso/app # Create a simple SAML SP test application cat <<'EOF' > app.py from flask import Flask, redirect, request, session import urllib.parse app = Flask(__name__) app.secret_key = 'lab-secret-key-change-in-production' KEYCLOAK_URL = "http://localhost:8080" REALM = "identitybytes" CLIENT_ID = "urn:identitybytes:saml:testapp" @app.route('/') def home(): user = session.get('user', None) if user: return f''' <h1>🎉 SSO Authentication Successful!</h1> <h2>Welcome, {user}!</h2> <p>You have been authenticated via SAML 2.0 SSO.</p> <p><a href="/logout">Logout</a></p> ''' return ''' <h1>Identity Bytes SAML Test App</h1> <p>This application demonstrates SAML 2.0 SSO with Keycloak.</p> <p><a href="/login">Login with SSO</a></p> ''' @app.route('/login') def login(): # Redirect to Keycloak login # In production, use proper SAML library (python3-saml) login_url = f"{KEYCLOAK_URL}/realms/{REALM}/protocol/saml" return redirect(login_url) @app.route('/saml/acs', methods=['POST']) def acs(): # Assertion Consumer Service - receives SAML Response saml_response = request.form.get('SAMLResponse', '') if saml_response: # In production, validate signature and parse assertion session['user'] = 'SAML User' return redirect('/') return 'No SAML Response received', 400 @app.route('/logout') def logout(): session.clear() return redirect('/') if __name__ == '__main__': app.run(host='0.0.0.0', port=8000, debug=True) EOF # Create requirements file cat <<'EOF' > requirements.txt flask==3.0.0 EOF cat app.py
17

Run the Test Application

Install the Python dependencies and start the test application. The app will listen on port 8000 and provide a simple interface to initiate SAML authentication.

Ubuntu VM
# Install Python dependencies cd ~/identity-bytes-labs/lab-02-saml-sso/app pip3 install -r requirements.txt --break-system-packages # Start the test application python3 app.py

Note: Keep this terminal open. Open a new terminal or browser for the next steps.

18

Test SAML Authentication Flow

Now test the complete SSO flow. Open your browser and navigate to the test application. Click "Login with SSO" to initiate SAML authentication. You'll be redirected to Keycloak's login page where you can authenticate with an LDAP user.

Web Browser
# Test SSO Flow: 1. Open browser: http://localhost:8000 2. Click "Login with SSO" 3. You'll be redirected to Keycloak login page 4. Enter credentials: Username: jdoe Password: SecureP@ss2024! 5. Click "Sign In" 6. You should be redirected back to the app showing "SSO Authentication Successful!" # Alternative: Test directly in Keycloak Account Console # http://localhost:8080/realms/identitybytes/account # Login with: jdoe / SecureP@ss2024!
19

View SAML Messages (Debug)

To understand what happens during SAML authentication, use browser developer tools to inspect the SAML messages. The SAML Response contains the assertion with user attributes and signature.

Web Browser
# Debug SAML Flow: 1. Open browser Developer Tools (F12) 2. Go to Network tab 3. Initiate SSO login again 4. Look for POST request to /saml/acs 5. In the request, find "SAMLResponse" form parameter 6. Copy the SAMLResponse value # Decode SAML Response: # Use an online tool like: https://www.samltool.com/decode.php # Or base64 decode: echo "[SAMLResponse value]" | base64 -d | xmllint --format - # The decoded XML shows: # - Issuer (Keycloak IdP) # - Subject (authenticated user) # - Conditions (validity period) # - AttributeStatement (user attributes) # - Signature (cryptographic proof)

✅ SSO Test Complete!

If you successfully logged in with jdoe's LDAP credentials and were redirected back to the application, your SAML SSO implementation is working! The user authenticated against Keycloak, which validated credentials against OpenLDAP.

🔧 Troubleshooting Guide

Common Issues and Solutions

Issue: "Invalid credentials" when logging in

Cause: LDAP password not syncing or wrong password

Solution:

  • Verify LDAP user can authenticate: ldapwhoami -x -H ldap://localhost -D "uid=jdoe,ou=people,dc=identitybytes,dc=lab" -w "SecureP@ss2024!"
  • Re-sync users in Keycloak: User Federation > OpenLDAP > Actions > Sync all users
  • Check LDAP federation is in READ_ONLY mode

Issue: "Unable to connect to LDAP server"

Cause: Network connectivity between containers

Solution:

  • Verify both containers are on sso-network: docker network inspect sso-network
  • Test connectivity from Keycloak: docker exec -it keycloak-idp /bin/bash -c "curl -v telnet://identitybytes-ldap:389"
  • Use IP address instead of hostname in Connection URL

Issue: Keycloak not starting

Cause: Database or memory issues

Solution:

  • Check logs: docker compose logs keycloak
  • Ensure PostgreSQL started first: docker compose logs postgres
  • Increase VM memory to 8GB if possible

🧹 Cleanup & Reset

20

Stop Lab Services

When you're finished with the lab, stop all services. You can choose to keep the data for later or perform a complete cleanup.

Ubuntu VM
# Stop test application (Ctrl+C in its terminal) # Stop Keycloak services (preserves data) cd ~/identity-bytes-labs/lab-02-saml-sso/docker docker compose stop # Complete cleanup (removes all data) docker compose down -v docker network rm sso-network # Remove lab directory rm -rf ~/identity-bytes-labs/lab-02-saml-sso

🎓 Key Takeaways

Skills Mastered in This Lab

Next Labs in the Series

📚 Additional Learning Resources

Continue your SAML and SSO learning journey with these carefully curated resources:

📖 Official Documentation
🎓 Online Courses
🔧 Tools & Utilities
📚 Books
  • Keycloak - Identity and Access Management for Modern Applications — Stian Thorgersen
  • Solving Identity Management in Modern Applications — Yvonne Wilson
  • Enterprise Single Sign-On Design Guide — IBM Redbooks

💡 Practice Recommendations

  • Extend this lab: Add a second SAML application and test true SSO (login once, access both)
  • Try different IdPs: Replicate this lab with Okta or Azure AD (free tiers available)
  • Enable HTTPS: Configure TLS certificates for Keycloak to simulate production
  • Add MFA: Configure Keycloak to require OTP as second factor
  • Explore OIDC: Configure the same client for OpenID Connect instead of SAML