Skip to content

Latest commit

 

History

History
729 lines (544 loc) · 16.6 KB

File metadata and controls

729 lines (544 loc) · 16.6 KB

Hướng Dẫn Test Federation Hub Providers

📋 Mục Lục

  1. Kiểm Tra Providers Đã Load
  2. Test Authenticator
  3. Test Protocol Mapper
  4. Test Event Listener
  5. Test REST API
  6. Test End-to-End

1. Kiểm Tra Providers Đã Load

Bước 1.1: Truy cập Admin Console

  1. Mở browser: http://localhost:8080
  2. Login với:
    • Username: admin
    • Password: admin

Bước 1.2: Xem Server Info

  1. Click Server Info ở menu bên trái (dưới cùng)
  2. Click tab Providers
  3. Tìm kiếm "federation" trong ô search

Bước 1.3: Verify Providers

Bạn sẽ thấy các providers sau:

✅ realm-restapi-extension

  • Provider ID: federation-hub
  • Class: FederationHubResourceProviderFactory
  • Purpose: REST API endpoints cho quản lý IdP và routing rules

✅ protocol-mapper

  • Provider ID: federation-partner-claims-mapper
  • Class: PartnerClaimsMapperFactory
  • Purpose: Map claims từ federated IdP vào Keycloak token

✅ authenticator

  • Provider ID: federation-hub-authenticator
  • Class: FederationHubAuthenticatorFactory
  • Purpose: Intelligent routing authenticator

✅ eventsListener

  • Provider ID: federation-audit
  • Class: FederationEventListenerProviderFactory
  • Purpose: Audit logging và event streaming

2. Test Authenticator

Bước 2.1: Tạo Authentication Flow Mới

  1. Vào AuthenticationFlows
  2. Click Create flow
  3. Nhập:
    • Name: Federation Hub Flow
    • Description: Test flow for federation hub
  4. Click Create

Bước 2.2: Thêm Federation Hub Authenticator

  1. Trong flow vừa tạo, click Add execution
  2. Tìm và chọn federation-hub-authenticator
  3. Click Add
  4. Set Requirement thành REQUIRED

Bước 2.3: Configure Authenticator

  1. Click icon ⚙️ (Settings) bên cạnh authenticator
  2. Cấu hình các options (nếu có)
  3. Click Save

Bước 2.4: Test Flow

  1. Vào Realm SettingsLogin
  2. Set Browser Flow thành Federation Hub Flow
  3. Logout và thử login lại
  4. Authenticator sẽ được trigger

3. Test Protocol Mapper

Bước 3.1: Tạo Client Scope

  1. Vào Client Scopes
  2. Click Create client scope
  3. Nhập:
    • Name: federation-claims
    • Type: Default
  4. Click Save

Bước 3.2: Thêm Federation Mapper

  1. Trong client scope vừa tạo, vào tab Mappers
  2. Click Add mapperBy configuration
  3. Tìm và chọn federation-partner-claims-mapper
  4. Configure:
    • Name: partner-claims
    • Token Claim Name: partner_info
    • Claim JSON Type: JSON
  5. Click Save

Bước 3.3: Assign to Client

  1. Vào Clients → Chọn client (ví dụ: admin-cli)
  2. Vào tab Client Scopes
  3. Click Add client scope
  4. Chọn federation-claims
  5. Click AddDefault

Bước 3.4: Test Mapper

  1. Get token mới:
$body = @{
    username = "admin"
    password = "admin"
    grant_type = "password"
    client_id = "admin-cli"
    scope = "openid profile email"
}

$response = Invoke-RestMethod -Uri "http://localhost:8080/realms/master/protocol/openid-connect/token" -Method Post -Body $body -ContentType "application/x-www-form-urlencoded"

# Decode token để xem claims
$token = $response.access_token
Write-Output $token
  1. Decode token tại https://jwt.io để xem claims

4. Test Event Listener

Bước 4.1: Enable Event Listener

  1. Vào Realm SettingsEvents
  2. Click tab Event Listeners
  3. Tìm federation-audit trong dropdown
  4. Click Add để thêm vào danh sách
  5. Click Save

Bước 4.2: Configure Event Types

  1. Vào tab User events settings
  2. Enable Save events
  3. Chọn event types muốn log:
    • Login
    • Login Error
    • Logout
    • Register
    • etc.
  4. Click Save

Bước 4.3: Trigger Events

  1. Logout khỏi Admin Console
  2. Login lại
  3. Thử login sai password
  4. Logout

Bước 4.4: Verify Events

  1. Vào EventsLogin events
  2. Xem các events đã được log
  3. Check logs:
docker logs keycloak-federation-hub | grep -i "federation.*event"

5. Test REST API

Bước 5.1: Get Admin Token

$body = @{
    username = "admin"
    password = "admin"
    grant_type = "password"
    client_id = "admin-cli"
}

$response = Invoke-RestMethod -Uri "http://localhost:8080/realms/master/protocol/openid-connect/token" -Method Post -Body $body -ContentType "application/x-www-form-urlencoded"

$token = $response.access_token

$headers = @{
    "Authorization" = "Bearer $token"
    "Content-Type" = "application/json"
}

Bước 5.2: Test List IdPs

# List all IdPs
try {
    $idps = Invoke-RestMethod -Uri "http://localhost:8080/realms/master/federation-hub/idps" -Headers $headers -Method Get
    Write-Output "Found $($idps.Count) IdPs"
    $idps | ConvertTo-Json
} catch {
    Write-Output "Error: $($_.Exception.Message)"
    Write-Output "Note: REST API may need additional configuration"
}

Bước 5.3: Test Create IdP

$idpConfig = @{
    displayName = "Google OIDC"
    protocol = "OIDC"
    enabled = $true
    config = @{
        authorizationUrl = "https://accounts.google.com/o/oauth2/v2/auth"
        tokenUrl = "https://oauth2.googleapis.com/token"
        userinfoUrl = "https://openidconnect.googleapis.com/v1/userinfo"
        clientId = "your-client-id"
        clientSecret = "your-client-secret"
        scope = "openid profile email"
    }
    mappers = @()
} | ConvertTo-Json

try {
    $result = Invoke-RestMethod -Uri "http://localhost:8080/realms/master/federation-hub/idps" -Headers $headers -Method Post -Body $idpConfig
    Write-Output "IdP created successfully!"
    $result | ConvertTo-Json
} catch {
    Write-Output "Error: $($_.Exception.Message)"
}

Bước 5.4: Test Routing Rules

# List routing rules
$rules = Invoke-RestMethod -Uri "http://localhost:8080/realms/master/federation-hub/routing-rules" -Headers $headers -Method Get
Write-Output "Found $($rules.Count) routing rules"

6. Test End-to-End

Scenario 1: Email Domain Routing

Setup

  1. Tạo 2 IdPs:

    • IdP 1: Google (cho @gmail.com)
    • IdP 2: Azure AD (cho @company.com)
  2. Tạo routing rule:

{
  "priority": 100,
  "enabled": true,
  "conditions": [
    {
      "field": "email_domain",
      "operator": "equals",
      "value": "gmail.com"
    }
  ],
  "targetIdpId": "google-oidc"
}

Test

  1. User với email user@gmail.com → Route to Google
  2. User với email user@company.com → Route to Azure AD

Scenario 2: Client-Based Routing

Setup

  1. Tạo routing rule cho specific client:
{
  "priority": 200,
  "enabled": true,
  "conditions": [
    {
      "field": "client_id",
      "operator": "equals",
      "value": "mobile-app"
    }
  ],
  "targetIdpId": "mobile-idp"
}

Test

  1. Login từ mobile-app client → Route to mobile-idp
  2. Login từ client khác → Route theo default

Scenario 3: Header-Based Routing

Setup

  1. Tạo routing rule dựa trên header:
{
  "priority": 150,
  "enabled": true,
  "conditions": [
    {
      "field": "header",
      "key": "X-Partner",
      "operator": "equals",
      "value": "partner-a"
    }
  ],
  "targetIdpId": "partner-a-idp"
}

Test

  1. Request với header X-Partner: partner-a → Route to partner-a-idp
  2. Request không có header → Route theo default

🔍 Debugging

Check Logs

# Real-time logs
docker logs -f keycloak-federation-hub

# Filter federation logs
docker logs keycloak-federation-hub 2>&1 | grep -i federation

# Check for errors
docker logs keycloak-federation-hub 2>&1 | grep -i error

# Check specific provider
docker logs keycloak-federation-hub 2>&1 | grep -i "federation-hub-authenticator"

Check Database

# Connect to PostgreSQL
docker exec -it keycloak-postgres psql -U keycloak -d keycloak

# Check federation tables
\dt federation_*

# View IdP configs
SELECT id, display_name, protocol, enabled FROM federation_idp_config;

# View routing rules
SELECT id, priority, enabled, target_idp_id FROM federation_routing_rule;

# Exit
\q

Check Cache

# Connect to Redis
docker exec -it keycloak-redis redis-cli

# List all keys
KEYS *

# Check federation cache keys
KEYS federation:*
KEYS idp:*

# Exit
exit

Check Kafka Events

# List topics
docker exec -it keycloak-kafka kafka-topics --list --bootstrap-server localhost:9092

# Consume federation events
docker exec -it keycloak-kafka kafka-console-consumer --bootstrap-server localhost:9092 --topic keycloak-federation-events --from-beginning

📊 Monitoring

Prometheus Metrics

  1. Mở http://localhost:9090
  2. Query các metrics:
    • keycloak_* - Keycloak metrics
    • jvm_* - JVM metrics
    • http_* - HTTP metrics

Grafana Dashboards

  1. Mở http://localhost:3000
  2. Login: admin/admin
  3. Import dashboards:
    • Keycloak Overview
    • Federation Hub Metrics
    • JVM Metrics

🧪 Test Scripts

Quick Test Script

# Save as test-quick.ps1
Write-Host "Quick Federation Hub Test" -ForegroundColor Cyan

# 1. Health Check
$health = Invoke-WebRequest -Uri "http://localhost:8080/health/ready" -UseBasicParsing
Write-Host "Health: $($health.StatusCode)" -ForegroundColor Green

# 2. Count Providers
$providers = docker logs keycloak-federation-hub 2>&1 | Select-String "federation-"
Write-Host "Providers: $($providers.Count)" -ForegroundColor Green

# 3. Check Services
$services = docker-compose ps --format json 2>$null | ConvertFrom-Json
$running = ($services | Where-Object { $_.State -eq "running" }).Count
Write-Host "Services: $running/$($services.Count) running" -ForegroundColor Green

Write-Host "`nAll systems operational!" -ForegroundColor Green

Full Test Script

# Save as test-full.ps1
# Run: .\test-full.ps1

# Get token
$body = @{
    username = "admin"
    password = "admin"
    grant_type = "password"
    client_id = "admin-cli"
}

$tokenResponse = Invoke-RestMethod -Uri "http://localhost:8080/realms/master/protocol/openid-connect/token" -Method Post -Body $body -ContentType "application/x-www-form-urlencoded"

$headers = @{
    "Authorization" = "Bearer $($tokenResponse.access_token)"
    "Content-Type" = "application/json"
}

# Test endpoints
Write-Host "Testing Federation Hub Endpoints..." -ForegroundColor Cyan

# 1. List IdPs
Write-Host "`n1. GET /federation-hub/idps"
try {
    $idps = Invoke-RestMethod -Uri "http://localhost:8080/realms/master/federation-hub/idps" -Headers $headers
    Write-Host "   Success: $($idps.Count) IdPs" -ForegroundColor Green
} catch {
    Write-Host "   Failed: $($_.Exception.Response.StatusCode)" -ForegroundColor Red
}

# 2. List Rules
Write-Host "`n2. GET /federation-hub/routing-rules"
try {
    $rules = Invoke-RestMethod -Uri "http://localhost:8080/realms/master/federation-hub/routing-rules" -Headers $headers
    Write-Host "   Success: $($rules.Count) rules" -ForegroundColor Green
} catch {
    Write-Host "   Failed: $($_.Exception.Response.StatusCode)" -ForegroundColor Red
}

# 3. Health Check
Write-Host "`n3. GET /federation-hub/health"
try {
    $health = Invoke-RestMethod -Uri "http://localhost:8080/realms/master/federation-hub/health" -Headers $headers
    Write-Host "   Success: Health check OK" -ForegroundColor Green
} catch {
    Write-Host "   Failed: $($_.Exception.Response.StatusCode)" -ForegroundColor Red
}

🎯 Test Cases

Test Case 1: Provider Loading

Objective: Verify all providers load successfully

Steps:

  1. Start Keycloak: docker-compose up -d
  2. Wait for startup: Start-Sleep -Seconds 30
  3. Check logs: docker logs keycloak-federation-hub | grep federation

Expected Result:

  • 4 providers loaded
  • No errors in logs
  • Providers visible in Server Info

Status: ✅ PASS


Test Case 2: Authenticator Registration

Objective: Verify authenticator is available in flows

Steps:

  1. Login to Admin Console
  2. Go to Authentication → Flows
  3. Create new flow
  4. Try to add execution

Expected Result:

  • federation-hub-authenticator appears in execution list
  • Can be added to flow
  • Can be configured

Status: ⏳ TO TEST


Test Case 3: Protocol Mapper Registration

Objective: Verify mapper is available for clients

Steps:

  1. Go to Clients → Select client
  2. Go to Client Scopes → Mappers
  3. Click Add Mapper → By Configuration

Expected Result:

  • federation-partner-claims-mapper appears in list
  • Can be added to client scope
  • Can be configured

Status: ⏳ TO TEST


Test Case 4: Event Listener Active

Objective: Verify events are captured and logged

Steps:

  1. Enable federation-audit in Event Listeners
  2. Perform login/logout
  3. Check logs for events

Expected Result:

  • Events captured
  • Logged to console/Kafka
  • Visible in Events tab

Status: ⏳ TO TEST


Test Case 5: REST API Endpoints

Objective: Verify REST API is accessible

Steps:

  1. Get admin token
  2. Call GET /federation-hub/idps
  3. Call GET /federation-hub/routing-rules

Expected Result:

  • Endpoints return 200 OK
  • Empty lists initially
  • Can create/update/delete resources

Status: ⚠️ NEEDS CONFIGURATION


🐛 Troubleshooting

Issue: Providers Not Visible

Solution:

# Rebuild and restart
docker-compose build keycloak
docker-compose restart keycloak

# Check logs
docker logs keycloak-federation-hub | grep -i "provider"

Issue: Authenticator Not in List

Solution:

  1. Clear browser cache
  2. Logout and login again
  3. Check Server Info → Providers
  4. Verify authenticator is loaded

Issue: REST API 404

Solution:

  1. Verify realm name is correct (master)
  2. Check token is valid
  3. Verify provider is loaded:
docker logs keycloak-federation-hub | grep "federation-hub"

Issue: Events Not Captured

Solution:

  1. Verify event listener is enabled in Realm Settings
  2. Check event types are selected
  3. Verify "Save events" is enabled
  4. Check logs:
docker logs keycloak-federation-hub | grep "FederationEvent"

📈 Performance Testing

Load Test Script

# test-load.ps1
$iterations = 100

Write-Host "Running $iterations authentication tests..."

for ($i = 1; $i -le $iterations; $i++) {
    $body = @{
        username = "admin"
        password = "admin"
        grant_type = "password"
        client_id = "admin-cli"
    }
    
    $start = Get-Date
    $response = Invoke-RestMethod -Uri "http://localhost:8080/realms/master/protocol/openid-connect/token" -Method Post -Body $body -ContentType "application/x-www-form-urlencoded"
    $duration = (Get-Date) - $start
    
    if ($i % 10 -eq 0) {
        Write-Host "Completed $i/$iterations (Avg: $($duration.TotalMilliseconds)ms)"
    }
}

Write-Host "Load test complete!"

Monitor During Load Test

# Watch metrics
watch -n 1 'docker stats keycloak-federation-hub --no-stream'

# Watch logs
docker logs -f keycloak-federation-hub | grep -i "federation"

✅ Acceptance Criteria

Must Have

  • All 4 providers load successfully
  • No errors during startup
  • Providers visible in Server Info
  • Event listener initialized
  • Authenticator works in flow
  • Protocol mapper adds claims
  • Events are captured

Should Have

  • REST API endpoints accessible
  • IdP CRUD operations work
  • Routing rules CRUD operations work
  • Health checks return status

Nice to Have

  • Grafana dashboards configured
  • Prometheus alerts setup
  • Kafka events streaming
  • Performance benchmarks

📚 Additional Resources

Documentation

Example Configurations

  • See deployment/examples/ for sample IdP configs
  • See deployment/examples/ for sample routing rules

Support

  • Check logs: docker logs keycloak-federation-hub
  • Check issues: GitHub Issues
  • Documentation: README.md

🎉 Success Indicators

Nếu bạn thấy:

  • ✅ 4 providers trong Server Info
  • ✅ Authenticator trong Authentication Flows
  • ✅ Mapper trong Client Scopes
  • ✅ Event Listener trong Events
  • ✅ No errors in logs

Thì Federation Hub đã hoạt động thành công! 🚀