> **Note (2026-11-30): this is the upstream README of the cloned base repo**
> ([IAMDevBox/keycloak-spring-boot-oauth2](https://github.com/IAMDevBox/keycloak-spring-boot-oauth2), MIT — see `NOTICE`),
> kept verbatim. It describes the original `demo` realm and endpoints, **not** this module as
> modified for the POC (`bqt` realm, accounts domain, MCP route, isolated DPoP filter). For this
> module read [`spec.md`](spec.md) and [`TESTING.md`](TESTING.md).

# keycloak-spring-boot-oauth2

Production-ready Spring Boot 3.x OAuth2 Resource Server with Keycloak integration. Features JWT validation, Keycloak realm role extraction, multi-tenant support, and Testcontainers integration tests.

📖 **Full tutorial**: [Keycloak Spring Boot OAuth2 Integration: Complete Developer Guide](https://www.iamdevbox.com/posts/keycloak-spring-boot-oauth2-integration-complete-guide/?utm_source=github&utm_medium=companion-repo&utm_campaign=keycloak-spring-boot-oauth2)

## Features

- Spring Boot 3.2+ with Spring Security 6.x OAuth2 Resource Server
- Keycloak JWT validation via JWKS auto-discovery
- Custom `KeycloakRoleConverter` — extracts `realm_access.roles` into Spring Security authorities
- Client-level role extraction from `resource_access`
- Token audience validation (prevents cross-service token reuse)
- Multi-tenant realm support with per-realm decoder caching
- Integration tests with Testcontainers Keycloak container
- Unit tests using Spring Security's `jwt()` mock
- Docker Compose for local Keycloak development

## Quick Start

### 1. Start Keycloak

```bash
docker compose -f docker/docker-compose.yml up -d
```

This starts Keycloak at `http://localhost:8080` with a pre-configured `demo` realm and test users.

### 2. Run the Application

```bash
./mvnw spring-boot:run
```

The app starts at `http://localhost:8081`.

### 3. Get a Token

```bash
# Get access token (user role)
TOKEN=$(curl -s -X POST \
  http://localhost:8080/realms/demo/protocol/openid-connect/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=password" \
  -d "client_id=demo-app" \
  -d "client_secret=demo-secret" \
  -d "username=testuser" \
  -d "password=password" | jq -r '.access_token')

# Call protected endpoint
curl -H "Authorization: Bearer $TOKEN" http://localhost:8081/api/profile
```

### 4. Test Admin Endpoint

```bash
# Get admin token
ADMIN_TOKEN=$(curl -s -X POST \
  http://localhost:8080/realms/demo/protocol/openid-connect/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=password" \
  -d "client_id=demo-app" \
  -d "client_secret=demo-secret" \
  -d "username=adminuser" \
  -d "password=password" | jq -r '.access_token')

curl -H "Authorization: Bearer $ADMIN_TOKEN" http://localhost:8081/api/admin/users
```

## Project Structure

```
src/
├── main/java/com/iamdevbox/keycloak/
│   ├── config/
│   │   └── SecurityConfig.java          # Security filter chain configuration
│   ├── security/
│   │   └── KeycloakRoleConverter.java   # Realm role → Spring authority converter
│   └── controller/
│       └── UserController.java          # Demo REST endpoints
└── test/java/com/iamdevbox/keycloak/
    ├── KeycloakIntegrationTest.java     # Testcontainers real Keycloak test
    └── UserControllerUnitTest.java      # JWT mock unit tests
```

## Key Configuration

### application.yml

```yaml
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:8080/realms/demo
```

### Keycloak Role Mapping

Keycloak places roles in `realm_access.roles` — this is different from standard OAuth2 scope claims. The included `KeycloakRoleConverter` handles this automatically:

```json
{
  "realm_access": {
    "roles": ["ROLE_USER", "ROLE_ADMIN"]
  }
}
```

Maps to Spring Security authorities: `ROLE_USER`, `ROLE_ADMIN`.

## Testing

```bash
# Run all tests (starts Keycloak via Testcontainers)
./mvnw test

# Run unit tests only (no Keycloak required)
./mvnw test -Dgroups=unit
```

## API Endpoints

| Method | Path | Role Required | Description |
|--------|------|--------------|-------------|
| GET | `/api/profile` | USER | Returns token claims for authenticated user |
| GET | `/api/admin/users` | ADMIN | Admin-only endpoint |
| GET | `/api/token-info` | Any authenticated | Returns full token metadata |
| GET | `/public/health` | None | Public health check |

## Related IAMDevBox Resources

- 📖 [Full Tutorial: Keycloak Spring Boot OAuth2 Integration](https://www.iamdevbox.com/posts/keycloak-spring-boot-oauth2-integration-complete-guide/?utm_source=github&utm_medium=companion-repo&utm_campaign=keycloak-spring-boot-oauth2)
- 🐳 [Keycloak Docker Compose Production Guide](https://www.iamdevbox.com/posts/keycloak-docker-compose-production-deployment-guide/?utm_source=github&utm_medium=companion-repo&utm_campaign=keycloak-spring-boot-oauth2)
- 🔐 [Keycloak Complete Guide](https://www.iamdevbox.com/posts/keycloak-complete-guide-open-source-iam-platform/?utm_source=github&utm_medium=companion-repo&utm_campaign=keycloak-spring-boot-oauth2)
- 🔑 [OAuth 2.0 PKCE Implementation](https://www.iamdevbox.com/posts/understanding-code_verifier-in-oauth-20-pkce-implementation-security-benefits-and-practical-examples/?utm_source=github&utm_medium=companion-repo&utm_campaign=keycloak-spring-boot-oauth2)
- 🛠️ [JWT Decode Tool](https://www.iamdevbox.com/tools/jwt-decode/?utm_source=github&utm_medium=companion-repo&utm_campaign=keycloak-spring-boot-oauth2)

## License

MIT License — see [LICENSE](LICENSE) file.
