# Keycloak Setup for B2B Flight Platform

This directory contains the Keycloak configuration for the B2B Flight Ticketing Platform.

## Prerequisites

- Docker and Docker Compose installed
- `jq` command-line JSON processor (for the setup script)
- `curl` command-line tool

## Quick Start

### 1. Start Keycloak

From the project root directory, start all services including Keycloak:

```bash
docker-compose up -d keycloak
```

Wait for Keycloak to be fully started (usually takes 30-60 seconds).

### 2. Import Realm Configuration

Run the setup script to create the realm and configure roles:

```bash
cd keycloak
chmod +x setup-keycloak.sh
./setup-keycloak.sh
```

### 3. Verify Setup

Access the Keycloak Admin Console:
- URL: http://localhost:8080/admin
- Username: `admin`
- Password: `admin`

Navigate to the `b2b-flight-platform` realm to verify:
- Roles are created (SUPER_ADMIN, AGENCY_ADMIN, HR_USER, FINANCE_USER, AGENT)
- Clients are configured (b2b-flight-backend, b2b-flight-frontend)
- Default super admin user exists

## Configuration Details

### Realm: b2b-flight-platform

**Security Settings:**
- SSL: Not required (development only)
- Brute force protection: Enabled
- Max login failures: 5
- Lockout duration: 15 minutes

### Roles

| Role | Description |
|------|-------------|
| SUPER_ADMIN | Platform administrator with full system access |
| AGENCY_ADMIN | Sub-agency administrator managing their agency |
| HR_USER | Human resources role within a sub-agency |
| FINANCE_USER | Financial management role within a sub-agency |
| AGENT | Standard user performing flight operations |

### OAuth 2.0 Clients

#### b2b-flight-backend (Confidential Client)
- Client ID: `b2b-flight-backend`
- Client Secret: `b2b-flight-backend-secret`
- Access Type: Confidential
- Standard Flow: Enabled
- Direct Access Grants: Enabled
- Service Accounts: Enabled
- Token Lifespan: 30 minutes (1800 seconds)

#### b2b-flight-frontend (Public Client)
- Client ID: `b2b-flight-frontend`
- Access Type: Public
- Standard Flow: Enabled
- Direct Access Grants: Enabled
- Token Lifespan: 30 minutes (1800 seconds)

### Multi-Factor Authentication (MFA)

**TOTP Configuration:**
- Algorithm: HmacSHA1
- Digits: 6
- Period: 30 seconds
- Supported Apps: Google Authenticator, Microsoft Authenticator

**MFA Enforcement:**
- MFA is required for SUPER_ADMIN and AGENCY_ADMIN roles
- Configured at the application level (not enforced by Keycloak directly)
- Users can set up TOTP via the "Configure OTP" required action

### Default Users

A default super admin user is created for initial setup:
- Username: `superadmin`
- Password: `SuperAdmin123!`
- Email: `superadmin@b2bflight.com`
- Role: SUPER_ADMIN

**⚠️ Important:** Change this password in production!

## Testing Authentication

### Get Access Token (Password Grant)

```bash
curl -X POST "http://localhost:8080/realms/b2b-flight-platform/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=b2b-flight-backend" \
  -d "client_secret=b2b-flight-backend-secret" \
  -d "grant_type=password" \
  -d "username=superadmin" \
  -d "password=SuperAdmin123!" \
  -d "scope=openid profile email"
```

### Decode JWT Token

Use https://jwt.io to decode and inspect the JWT token.

### Refresh Token

```bash
curl -X POST "http://localhost:8080/realms/b2b-flight-platform/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=b2b-flight-backend" \
  -d "client_secret=b2b-flight-backend-secret" \
  -d "grant_type=refresh_token" \
  -d "refresh_token=YOUR_REFRESH_TOKEN"
```

### Logout (Revoke Token)

```bash
curl -X POST "http://localhost:8080/realms/b2b-flight-platform/protocol/openid-connect/logout" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=b2b-flight-backend" \
  -d "client_secret=b2b-flight-backend-secret" \
  -d "refresh_token=YOUR_REFRESH_TOKEN"
```

## Manual Configuration (Alternative)

If you prefer to configure Keycloak manually through the Admin Console:

1. Access http://localhost:8080/admin
2. Create a new realm named `b2b-flight-platform`
3. Create the five roles listed above
4. Create the two OAuth clients with the settings above
5. Configure TOTP under Authentication > Required Actions
6. Create the default super admin user

## Troubleshooting

### Keycloak not starting
- Check if port 8080 is already in use
- Verify PostgreSQL is running and healthy
- Check logs: `docker logs b2b-flight-keycloak`

### Setup script fails
- Ensure Keycloak is fully started before running the script
- Verify `jq` is installed: `which jq`
- Check if realm already exists (script will skip if it does)

### Cannot get access token
- Verify the realm name is correct
- Check client ID and secret
- Ensure user credentials are correct
- Check Keycloak logs for authentication errors

## Production Considerations

For production deployment:

1. **Enable SSL/TLS**: Set `sslRequired` to `external` or `all`
2. **Change Default Passwords**: Update admin and superadmin passwords
3. **Rotate Client Secrets**: Generate new client secrets
4. **Configure Email**: Set up SMTP for password reset and notifications
5. **Backup Configuration**: Export realm configuration regularly
6. **Database**: Use a dedicated PostgreSQL instance (not shared with application)
7. **High Availability**: Deploy multiple Keycloak instances behind a load balancer
8. **Monitoring**: Enable metrics and health checks
9. **Session Management**: Configure appropriate session timeouts
10. **Rate Limiting**: Implement rate limiting for authentication endpoints

## References

- [Keycloak Documentation](https://www.keycloak.org/documentation)
- [OAuth 2.0 Specification](https://oauth.net/2/)
- [OpenID Connect](https://openid.net/connect/)
- [TOTP RFC 6238](https://tools.ietf.org/html/rfc6238)
