Table of Contents

This comprehensive lab takes you from IAM fundamentals through building a complete identity platform. Each module builds upon the previous, starting with core concepts and progressing to advanced authorization patterns. The lab is structured so you can complete it in one extended session (6-8 hours) or tackle individual modules across multiple days.

Lab Overview & What You Will Build

Identity and Access Management (IAM) is the foundation of enterprise security—controlling who can access what resources under which conditions. In this comprehensive lab, you will build a complete IAM platform using Keycloak, an enterprise-grade open-source Identity Provider. You'll progress from deploying the platform through configuring users, groups, and roles, implementing authentication policies including multi-factor authentication, integrating real applications using OpenID Connect, and finally implementing fine-grained authorization with Role-Based Access Control (RBAC).

Prerequisites

This lab assumes familiarity with basic Linux commands and Docker. Prior completion of LAB 1 (LDAP) and LAB 2 (SAML) is helpful but not required—all necessary concepts are explained.

What You Will Build

Learning Objectives

Enterprise Scenario: Building the Identity Foundation

You've been hired as an IAM Engineer at TechStart Inc., a rapidly growing company that just reached 500 employees. The company has been using ad-hoc authentication methods. The CISO has tasked you with a critical project:

"We need a unified identity platform. Employees should have one identity that works across all applications. We need proper access controls—developers shouldn't have the same access as finance. And we need audit trails showing who accessed what and when."

  • Design identity architectures that scale from 10 to 10,000+ users
  • Implement SSO so users authenticate once and access all applications
  • Build access control models that enforce principle of least privilege
  • Integrate applications using industry-standard protocols (OIDC, SAML)

Skills You Will Gain & How They Apply

IAM Architecture

Design identity systems from scratch. Applies to Okta, Azure AD, Ping Identity, ForgeRock.

Protocol Expertise

Deep understanding of OIDC/OAuth2 flows. Essential for API security and microservices.

Access Control Design

RBAC implementation patterns. Foundation for ABAC, ReBAC, and zero-trust architectures.

Security Engineering

Authentication hardening, session management, MFA. Core security skills.

Identity Federation

Connect multiple identity sources. Required for B2B integrations and partner ecosystems.

Compliance Knowledge

Audit logging and access reviews. Addresses SOC 2, GDPR, HIPAA requirements.

IAM Fundamentals: Core Concepts & Theory

Before building an IAM system, you must understand the fundamental concepts that underpin all identity and access management solutions. These concepts apply regardless of which IAM product you use—whether Keycloak, Okta, Azure AD, or custom solutions.

What is Identity and Access Management?

Identity and Access Management (IAM) is a framework of policies, processes, and technologies that ensures the right individuals have appropriate access to technology resources. IAM addresses four fundamental questions:

  1. Who are you? (Identity) — Establishing and verifying digital identities
  2. How do I know it's really you? (Authentication) — Proving identity claims
  3. What are you allowed to do? (Authorization) — Determining permissions
  4. What did you do? (Accounting/Auditing) — Recording actions for accountability

The AAA Model + Identity

Identity

A digital representation of a person, system, or service. Includes attributes like username, email, employee ID.

Authentication (AuthN)

The process of verifying that someone is who they claim to be. Methods include passwords, biometrics, certificates.

Authorization (AuthZ)

The process of determining what an authenticated identity is permitted to do. Based on roles, attributes, policies.

Accounting (Audit)

Recording who did what, when, and from where. Creates accountability and supports compliance.

The Identity Lifecycle

Every identity goes through a lifecycle from creation to deletion:

IDENTITY LIFECYCLE STAGES

PROVISIONING

Create identity

MANAGEMENT

Update access

USAGE

Auth events

REVIEW

Access audit

DEPROVISION

Disable/Delete

Authentication Methods

Factor TypeDescriptionExamplesStrength
Something You KnowKnowledge-based secretsPasswords, PINsWeakest
Something You HavePhysical possessionPhone (TOTP), hardware tokensModerate
Something You AreBiometric characteristicsFingerprint, face recognitionStrongest

Multi-Factor Authentication (MFA)

MFA requires two or more factors from different categories. A password + security question is NOT MFA (both are "something you know"). A password + TOTP code IS MFA. Microsoft reports 99.9% reduction in account attacks with MFA.

Authorization Models

DAC (Discretionary)

Resource owners control access. Like file permissions. Flexible but hard to audit at scale.

MAC (Mandatory)

Central authority controls access based on classification levels. Used in military/government.

RBAC (Role-Based)

Access based on job function. Users assigned to roles; roles have permissions. Most common enterprise model.

ABAC (Attribute-Based)

Access based on attributes: user, resource, environment. Most flexible. "Allow if user.dept == resource.dept"

Key IAM Protocols

ProtocolPrimary UseToken TypeWhen to Use
SAML 2.0Enterprise SSOXML assertionsTraditional enterprise apps
OAuth 2.0Delegated authorizationAccess tokensAPI access, third-party apps
OpenID ConnectAuthentication + identityID tokens (JWT)Modern web/mobile apps
LDAPDirectory servicesN/A (query protocol)User/group storage

Prerequisites & Lab Environment

This lab runs entirely in a home lab environment using Docker containers. Keycloak is resource-efficient and runs well on modest hardware. The entire setup can be completed in under 30 minutes.

Required Components

ComponentRequirementPurpose
Host Machine4GB RAM minimum, 8GB recommendedRun Docker and containers
Docker EngineDocker 20.10+ or Docker DesktopContainer runtime
Docker Composev2.0+ (included in Docker Desktop)Multi-container orchestration
Web BrowserChrome, Firefox, or EdgeKeycloak admin console

Device Badges Legend

Local MachineDocker host / terminal
Keycloak ConsoleAdmin web interface
Web BrowserTesting and verification

Lab Architecture Overview

This diagram shows the complete IAM environment you'll build. The architecture represents a common enterprise pattern: a central Identity Provider (Keycloak) that handles authentication and authorization for multiple applications.

IAM PLATFORM ARCHITECTURE

USERS & IDENTITIES

Internal Users | External Users | Service Accounts

OIDC / SAML
IDENTITY PROVIDER (KEYCLOAK)

Authentication | Authorization | User Federation | Session Management

Access Tokens
APPLICATIONS & SERVICES

Web Apps | APIs | Microservices

User Data
IDENTITY SOURCES

Local Database | LDAP | Social Providers

KEYCLOAK COMPONENTS

AUTHENTICATION

Login flows, MFA

AUTHORIZATION

Roles, Permissions

ADMINISTRATION

Users, Groups

AUDIT & EVENTS

Login events

Module 1: Identity Provider Deployment

Module 1: Deploy Keycloak Identity Provider

Set up Keycloak using Docker Compose with production-ready configuration patterns.

30-45 minutes5 stepsLocal Machine

Keycloak is an open-source Identity and Access Management solution developed by Red Hat. It provides single sign-on, identity brokering, user federation, and fine-grained authorization. Used by organizations ranging from startups to Fortune 500 companies.

About Keycloak

  • Single Sign-On (SSO): Users authenticate once and access multiple applications
  • Identity Brokering: Connect to external identity providers (Google, Facebook, SAML IdPs)
  • User Federation: Sync users from LDAP, Active Directory
  • Standard Protocols: Full support for OIDC, OAuth 2.0, and SAML 2.0
1

Create Lab Directory Structure

Create a directory structure for the lab configuration files and persistent data.

Local Machine
mkdir -p ~/lab5-iam/{keycloak,app,data} cd ~/lab5-iam echo "Lab 5 IAM Directory Created: $(pwd)"
2

Create Docker Compose Configuration

Create a Docker Compose file that defines Keycloak and a PostgreSQL database for persistent storage.

Local Machine
cat > ~/lab5-iam/docker-compose.yml << 'EOF' version: '3.9' services: postgres: image: postgres:15-alpine container_name: keycloak-db environment: POSTGRES_DB: keycloak POSTGRES_USER: keycloak POSTGRES_PASSWORD: keycloak_db_password volumes: - postgres_data:/var/lib/postgresql/data networks: - iam-network healthcheck: test: ["CMD-SHELL", "pg_isready -U keycloak"] interval: 10s timeout: 5s retries: 5 keycloak: image: quay.io/keycloak/keycloak:23.0 container_name: keycloak command: start-dev environment: KEYCLOAK_ADMIN: admin KEYCLOAK_ADMIN_PASSWORD: admin KC_DB: postgres KC_DB_URL: jdbc:postgresql://postgres:5432/keycloak KC_DB_USERNAME: keycloak KC_DB_PASSWORD: keycloak_db_password KC_HOSTNAME: localhost KC_HTTP_ENABLED: true KC_HEALTH_ENABLED: true ports: - "8080:8080" depends_on: postgres: condition: service_healthy networks: - iam-network sample-app: image: nginx:alpine container_name: sample-app ports: - "3000:80" volumes: - ./app:/usr/share/nginx/html:ro networks: - iam-network volumes: postgres_data: networks: iam-network: driver: bridge EOF echo "Docker Compose file created"
3

Start the IAM Platform

Launch all containers. Keycloak takes 30-60 seconds to fully start after the container is running.

Local Machine
cd ~/lab5-iam docker compose up -d echo "Waiting for Keycloak to start..." sleep 30 docker compose ps docker compose logs keycloak | tail -20
4

Access Keycloak Admin Console

Open your web browser and navigate to the Keycloak admin console.

Web Browser
1. Open: http://localhost:8080 2. Click "Administration Console" 3. Username: admin 4. Password: admin 5. Click "Sign In"

Module 1 Complete!

Keycloak is now running and accessible. In Module 2, we'll create a dedicated realm and set up users and groups.

Module 2: Realm & User Management

Module 2: Create Realm, Users, and Groups

Build an organizational identity structure with realms for isolation and users/groups for access management.

45-60 minutes8 stepsKeycloak Console

In Keycloak, a realm is a complete isolation boundary—like a separate tenant. Each realm has its own users, groups, clients, and settings. Organizations typically use the master realm only for administration.

5

Create Application Realm

Create a new realm for our fictional company "TechStart".

Keycloak Console
1. Click the dropdown in the top-left (showing "master") 2. Click "Create Realm" 3. Realm name: techstart 4. Enabled: ON 5. Click "Create"
6

Create Organizational Groups

Create groups representing organizational structure.

Keycloak Console
Navigate to: Groups Create group Create these groups: 1. Engineering 2. Finance 3. Operations 4. Management Create sub-groups under Engineering: - Backend, Frontend, DevOps, QA
7

Create Test Users

Create several users representing different roles in the organization.

Keycloak Console
Navigate to: Users Add user User 1 - Developer: Username: alice.developer | Email: alice@techstart.local Password: Password123! | Groups: Engineering Backend User 2 - Manager: Username: bob.manager | Email: bob@techstart.local Password: Password123! | Groups: Management, Engineering User 3 - Finance: Username: carol.finance | Email: carol@techstart.local Password: Password123! | Groups: Finance User 4 - Admin: Username: dave.admin | Email: dave@techstart.local Password: Password123! | Groups: Operations
8

Create Realm Roles

Create roles that represent permissions or job functions.

Keycloak Console
Navigate to: Realm roles Create role Create these roles: 1. employee - Base role for all employees 2. developer - Software development access 3. manager - Team management access 4. admin - Administrative access 5. finance-viewer - Read-only finance access 6. finance-editor - Full finance access
9

Assign Roles to Groups

Assign roles to groups so all group members automatically receive those roles.

Keycloak Console
Navigate to: Groups Engineering Role mapping Assign: employee, developer Navigate to: Groups Management Role mapping Assign: employee, manager Navigate to: Groups Finance Role mapping Assign: employee, finance-viewer, finance-editor Navigate to: Groups Operations Role mapping Assign: employee, admin

Module 2 Complete!

You've created a complete organizational structure with a realm, groups, users, and roles.

Module 3: Authentication Policies & MFA

Module 3: Secure Authentication Configuration

Implement password policies, brute-force protection, and multi-factor authentication options.

45-60 minutes6 stepsKeycloak Console

Strong authentication is the first line of defense in any IAM system. Weak passwords, missing brute-force protection, and lack of MFA are responsible for the majority of account compromises.

10

Configure Password Policy

Keycloak Console
Navigate to: Authentication Policies Password policy Add these policies: 1. Minimum length: 12 2. Uppercase characters: 1 3. Lowercase characters: 1 4. Digits: 1 5. Special characters: 1 6. Not username 7. Password history: 5 8. Password age (days): 90
11

Enable Brute-Force Protection

Keycloak Console
Navigate to: Realm Settings Security defenses Brute force detection 1. Enabled: ON 2. Permanent lockout: OFF 3. Max login failures: 5 4. Wait increment (seconds): 60 5. Max wait (seconds): 900
12

Configure Session Settings

Keycloak Console
Navigate to: Realm Settings Sessions 1. SSO Session Idle: 30 minutes 2. SSO Session Max: 8 hours 3. Access Token Lifespan: 5 minutes
13

Configure OTP (TOTP) Settings

Keycloak Console
Navigate to: Authentication Policies OTP policy 1. OTP type: Time-based (totp) 2. OTP hash algorithm: SHA256 3. Number of digits: 6 4. OTP token period: 30 seconds

Module 3 Complete!

Your realm now has enterprise-grade authentication security.

Module 4: Application Integration (OIDC)

Module 4: Protect Applications with OIDC

Create an OIDC client and integrate a sample application to demonstrate the authentication flow.

60-90 minutes8 stepsKeycloak + Local Machine

OpenID Connect (OIDC) is the modern standard for application authentication. When a user accesses your application, they're redirected to Keycloak for authentication. After successful login, Keycloak returns tokens containing the user's identity and permissions.

OpenID Connect Flow

  1. User visits your application
  2. Application redirects to Keycloak's /auth endpoint
  3. User authenticates with Keycloak
  4. Keycloak redirects back with an authorization code
  5. Application exchanges code for tokens
  6. Application receives: ID Token (who), Access Token (permissions), Refresh Token
14

Create OIDC Client in Keycloak

Keycloak Console
Navigate to: Clients Create client General Settings: 1. Client type: OpenID Connect 2. Client ID: sample-app 3. Click "Next" Capability config: 4. Client authentication: ON 5. Authorization: ON 6. Click "Next" Login settings: 7. Root URL: http://localhost:3000 8. Valid redirect URIs: http://localhost:3000/* 9. Web origins: http://localhost:3000 10. Click "Save"
15

Configure Client Roles

Keycloak Console
Navigate to: Clients sample-app Roles Create these client roles: 1. app-user - Basic application access 2. app-admin - Application administration 3. app-viewer - Read-only access
16

Create Sample Application

Local Machine
cat > ~/lab5-iam/app/index.html << 'EOF' Sample App - IAM Lab 5

IAM Lab 5 - Sample Application

Welcome! Please login to access the application.

Assigned Roles

Roles:

EOF docker compose restart sample-app echo "Sample application created"
17

Test the Authentication Flow

Web Browser
1. Open: http://localhost:3000 2. Click "Login with Keycloak" 3. Enter credentials: alice.developer / Password123! 4. Observe user information and roles displayed 5. Click "Logout" to end the session

Module 4 Complete!

You've integrated an application with Keycloak using OpenID Connect!

Module 5: Role-Based Access Control (RBAC)

Module 5: Implement RBAC Authorization

Design and implement role hierarchies, permission mappings, and access control decisions.

45-60 minutes5 stepsKeycloak + App

Authentication answers "who are you?" but authorization answers "what can you do?" Role-Based Access Control (RBAC) is the most common authorization model in enterprise environments.

18

Create Role Hierarchy

Keycloak Console
Navigate to: Realm roles Create role 1. Role name: senior-developer Save Add associated roles: developer, employee 2. Role name: team-lead Save Add associated roles: senior-developer, manager Now team-lead has: employee + developer + senior-developer + manager
19

Assign Hierarchical Roles

Keycloak Console
Navigate to: Users bob.manager Role mapping 1. Assign: team-lead 2. Verify inherited roles: manager, senior-developer, developer, employee
20

Test RBAC with Different Users

Web Browser
Test at http://localhost:3000 with different users: 1. alice.developer Roles: employee, developer 2. bob.manager Roles: employee, developer, senior-developer, manager, team-lead 3. carol.finance Roles: employee, finance-viewer, finance-editor 4. dave.admin Roles: employee, admin

Module 5 Complete!

You've implemented Role-Based Access Control with role hierarchies!

Module 6: Groups, Attributes & Fine-Grained Permissions

Module 6: Advanced Authorization Patterns

Use groups for bulk management and attributes for fine-grained access control decisions.

30-45 minutes4 stepsKeycloak Console

While RBAC handles most authorization needs, some scenarios require more granular control. User and group attributes enable Attribute-Based Access Control (ABAC) patterns.

21

Add Group Attributes

Keycloak Console
Navigate to: Groups Engineering Attributes Add: 1. cost_center CC-ENG-100 2. data_classification internal Navigate to: Groups Finance Attributes 1. cost_center CC-FIN-200 2. data_classification confidential
22

Create Group Membership Mapper

Keycloak Console
Navigate to: Client scopes sample-app-dedicated Mappers Add mapper Select: Group Membership 1. Name: group_membership 2. Token Claim Name: groups 3. Add to ID token: ON 4. Add to access token: ON

Module 6 Complete!

You've configured groups and attributes for fine-grained authorization.

Module 7: Identity Federation & External Providers

Module 7: Connect External Identity Sources

Configure identity federation to accept users from external identity providers and directories.

45-60 minutes5 stepsKeycloak Console

Identity federation allows users to authenticate using credentials from external systems—social providers (Google, Microsoft), enterprise directories (Active Directory), or partner identity providers (SAML).

Federation Concepts

  • Identity Provider (IdP): The system that authenticates users
  • Service Provider (SP): The system that trusts the IdP (Keycloak)
  • Identity Brokering: Keycloak acts as a broker between your apps and external IdPs
  • Just-in-Time Provisioning: Creating accounts automatically on first login
23

Explore Identity Provider Options

Keycloak Console
Navigate to: Identity providers Add provider Available provider types: - Social: Google, Facebook, Twitter, GitHub, LinkedIn, Microsoft - Enterprise: SAML v2.0, OpenID Connect v1.0, OAuth 2.0 - Legacy: Kerberos, LDAP (via User Federation)
24

Configure Default Roles for Federated Users

Keycloak Console
Navigate to: Realm settings User registration Default roles 1. Click "Assign role" 2. Select: employee 3. Click "Assign" All new users (including federated) get the "employee" role.

Module 7 Complete!

You've explored identity federation and how to connect external identity providers.

Common Vulnerabilities & Best Practices

IAM systems are high-value targets for attackers because compromising them provides access to everything they protect. Understanding common vulnerabilities helps you design more secure systems.

CRITICAL

Token Theft and Replay

Access tokens stolen from logs, browser storage, or network traffic can be used to impersonate users.

Attack Scenario

An attacker finds an access token in application logs and uses it to access APIs as the victim.

Mitigation
  • Use short-lived access tokens (5-15 minutes)
  • Always use HTTPS in production
  • Never log tokens
  • Implement token binding
CRITICAL

OAuth Redirect Vulnerabilities

Open redirectors and improper redirect URI validation can allow attackers to steal authorization codes.

Mitigation
  • Use exact redirect URI matching
  • Validate state parameter
  • Use PKCE for all OAuth flows
HIGH

Privilege Escalation via Role Manipulation

Improper role assignment controls allow users to gain elevated privileges.

Mitigation
  • Implement role assignment approval workflows
  • Use server-side role validation
  • Audit all privilege changes
MEDIUM

Account Enumeration

Different error messages for valid vs. invalid usernames allow attackers to discover valid accounts.

Mitigation
  • Use generic error messages
  • Implement consistent response times
  • Rate limit authentication attempts

IAM Security Best Practices Checklist

  • Use HTTPS everywhere (no exceptions in production)
  • Implement strong password policies (12+ characters)
  • Enable MFA for all privileged accounts
  • Use short-lived access tokens (5-15 minutes)
  • Validate all redirect URIs exactly
  • Implement PKCE for all OAuth/OIDC flows
  • Enable brute-force protection
  • Audit all authentication events
  • Implement principle of least privilege
  • Regular access reviews and certification

Lab vs Production Configuration

SettingLab ValueProduction Value
HTTPSDisabled (HTTP)Required everywhere
Admin Password"admin"Strong, unique + MFA
Keycloak Modestart-devstart (production)
DatabasePostgreSQL (basic)HA PostgreSQL + encryption
Access Token5 minutes5-15 minutes (risk-based)

Key Takeaways

Congratulations on completing this comprehensive IAM lab! You've built a complete identity platform from the ground up, implementing patterns used by enterprise organizations worldwide.

Core Concepts Mastered

How These Skills Transfer

What You LearnedApplies To
Keycloak administrationOkta, Azure AD, Auth0, Ping Identity, ForgeRock
OIDC integrationAny modern web/mobile application, API security
RBAC designAWS IAM, GCP IAM, Kubernetes RBAC
Token validationMicroservices security, API gateways
Federation conceptsB2B integrations, partner ecosystems

What's Next

Additional Learning Resources

Continue your IAM journey with these carefully curated resources covering advanced topics, certification preparation, and enterprise implementation patterns.

Official Documentation
Enterprise IAM Platforms
Security Standards
Certifications
Practice & Tools
Advanced Topics

Practice Recommendations

  • Deploy Keycloak in the cloud: Set up on AWS/Azure/GCP with HTTPS
  • Integrate a real application: Add Keycloak authentication to an existing project
  • Implement SAML: Configure SAML alongside OIDC
  • Set up LDAP federation: Deploy OpenLDAP and federate users
  • Build an API gateway: Use Kong with Keycloak for API authentication
  • Study for certifications: Use this lab as foundation for Okta or Microsoft IAM certs