Skip to content

Teyoh-org/springboot-keycloak-security

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Spring Boot Keycloak Security Library

A comprehensive, easy-to-install Spring Boot security library that integrates seamlessly with Keycloak for authentication and authorization.

πŸš€ Features

  • βœ… User Registration & Authentication - Complete user management with Keycloak
  • βœ… JWT Token Security - Stateless JWT-based authentication
  • βœ… Role & Group Management - Assign and manage user roles and groups
  • βœ… Password Reset - Built-in password reset functionality
  • βœ… User Profile Management - Update user profiles and information
  • βœ… Token Refresh - Automatic token refresh support
  • βœ… Easy Configuration - Simple setup with environment variables
  • βœ… RESTful API - Clean REST endpoints for all operations

πŸ“‹ Prerequisites

  • Java 21 or higher
  • Maven 3.6 or higher
  • Docker and Docker Compose (recommended for easy setup)
  • OR Keycloak server (version 26.0.2 or compatible) if running manually
  • Spring Boot 3.4.0 or higher

Note: This setup is configured for development - HTTP is enabled and SSL is not required. For production, you should configure HTTPS and proper SSL settings.

πŸš€ Quick Start with Docker Compose (Recommended)

The easiest way to get started is using Docker Compose, which sets up Keycloak, PostgreSQL, and the Spring Boot application automatically.

1. Clone the Repository

git clone https://github.com/your-username/springboot-keycloak-security.git
cd springboot-keycloak-security

2. Start All Services

docker-compose up -d

This will:

  • Start PostgreSQL database for Keycloak
  • Start Keycloak server (realm import is optional - see below)
  • Build and start the Spring Boot application

Wait about 30-60 seconds for all services to start up completely.

3. Set Up Keycloak Realm

You have two options:

Option A: Use the Provided Realm (Optional) If you want to use the pre-configured realm from realm-export.json:

  1. Set environment variable to enable import:
    echo "KEYCLOAK_IMPORT_REALM=true" >> .env
  2. Restart Keycloak:
    docker-compose restart keycloak
  3. Wait for import to complete (~30 seconds)
  4. Note: The imported realm has SSL disabled, but you may still need to disable SSL for the master realm to access the admin console (see step 4)

Option B: Create Your Own Realm (Recommended for First Time)

  1. Wait for Keycloak to start (~30-60 seconds)
  2. Access the admin console:
  3. Login with:
    • Username: admin
    • Password: admin (or your configured KEYCLOAK_ADMIN_PASSWORD)
  4. Click Create Realm button
  5. Enter realm name (e.g., my-realm)
  6. Click Create
  7. Go to Realm Settings β†’ Security tab
  8. Set Require SSL to none (for development)
  9. Click Save
  10. Create a client:
    • Go to Clients β†’ Create Client
    • Client ID: user-management-service (or your preferred name)
    • Client Protocol: openid-connect
    • Enable Client authentication (confidential client)
    • Enable Service accounts roles (for admin operations)
    • Set Valid redirect URIs: http://localhost:8083/*
    • Click Save
    • Go to Credentials tab and copy the Secret

4. Disable SSL for Master Realm (First Time Only - Only if using Option A)

On first startup, the master realm requires SSL. To disable it for development:

Option 1: Via Admin Console (Recommended)

  1. Wait for Keycloak to fully start (about 30-60 seconds)
  2. Access the admin console directly: http://localhost:8080/admin/master/console/
    • (This direct URL bypasses the SSL redirect)
  3. Login with:
    • Username: admin
    • Password: admin (or your configured KEYCLOAK_ADMIN_PASSWORD)
  4. Go to Realm Settings (left sidebar) β†’ Security tab
  5. Set Require SSL dropdown to none
  6. Click Save

Option 2: Via Script (After first login) After you've logged in once and disabled SSL manually, you can use the script for future setups:

./init-master-realm.sh

Note: After disabling SSL, you can access the admin console normally at http://localhost:8080

5. Configure Spring Boot Application

  1. Create/update your .env file with your Keycloak configuration:

    cat > .env << EOF
    KEYCLOAK_REALM=my-realm
    KEYCLOAK_SERVER_URL=http://keycloak:8080
    KEYCLOAK_CLIENT_ID=user-management-service
    KEYCLOAK_CLIENT_SECRET=your-client-secret-here
    KEYCLOAK_ADMIN_USERNAME=admin
    KEYCLOAK_ADMIN_PASSWORD=admin
    KEYCLOAK_ADMIN_CLIENT_ID=admin-cli
    SERVER_PORT=8083
    EOF

    Replace your-client-secret-here with the secret from your client (see step 3)

  2. Restart the Spring Boot app:

    docker-compose restart springboot-app

Note: The Spring Boot app will start without the secret, but you need it for full functionality. You can also create the .env file before starting services if you prefer.

6. Verify Services

7. Stop Services

docker-compose down

To remove volumes (database data):

docker-compose down -v

πŸ”§ Manual Setup (Without Docker)

1. Add Dependency

<dependency>
    <groupId>io.teyoh</groupId>
    <artifactId>springboot-keycloak-security</artifactId>
    <version>1.0.0</version>
</dependency>

2. Set Up Keycloak

  1. Install and start Keycloak server (version 26.0.2)
  2. Access Keycloak Admin Console (typically http://localhost:8080)
  3. Import the realm from src/main/resources/realm-export.json:
    • Go to Realm Settings β†’ Import
    • Select the realm-export.json file
    • Click Import
  4. Get the client secret:
    • Navigate to Clients β†’ user-management-service β†’ Credentials
    • Copy the Secret value

3. Configure Environment Variables

export KEYCLOAK_REALM=my-realm
export KEYCLOAK_SERVER_URL=http://localhost:8080
export KEYCLOAK_CLIENT_ID=user-management-service
export KEYCLOAK_CLIENT_SECRET=your-client-secret-here
export KEYCLOAK_ADMIN_USERNAME=admin
export KEYCLOAK_ADMIN_PASSWORD=admin
export KEYCLOAK_ADMIN_CLIENT_ID=admin-cli
export SERVER_PORT=8083

Or create a .env file with these variables.

4. Run the Application

mvn spring-boot:run

πŸ“š API Endpoints

Authentication

  • POST /auth/login - User login
  • POST /auth/logout - User logout
  • POST /auth/refresh-token - Refresh access token
  • POST /auth/reset-password-request - Request password reset
  • POST /auth/reset-password - Reset password with token

User Management

  • GET /auth/users/me - Get current user profile
  • GET /auth/users/{userId} - Get user by ID
  • PUT /auth/users/{userId} - Update user profile
  • POST /auth/users/{userId}/roles - Assign role to user

πŸ” Keycloak Configuration

Using the Provided Realm Export

The project includes a pre-configured realm export (src/main/resources/realm-export.json) that contains:

  • Realm: my-realm
  • Client: user-management-service (configured with service account)
  • Default roles and settings

With Docker Compose: The realm is automatically imported on first startup.

Manual Import:

  1. Log into Keycloak Admin Console
  2. Select the master realm (or create a new one)
  3. Click Import in the realm selector dropdown
  4. Select src/main/resources/realm-export.json
  5. Click Import

Getting the Client Secret

After importing the realm:

  1. Navigate to Clients β†’ user-management-service
  2. Go to the Credentials tab
  3. Copy the Secret value
  4. Update your .env file or environment variables with KEYCLOAK_CLIENT_SECRET

Note: The realm export has a masked secret (**********), so you must get the actual secret from Keycloak after import.

Creating a Custom Client (Optional)

If you want to create your own client instead:

  1. Go to Clients β†’ Create Client
  2. Set Client ID: your-client-id
  3. Set Client Protocol: openid-connect
  4. Enable Client authentication (confidential client)
  5. Enable Service accounts roles (for admin operations)
  6. Set Valid redirect URIs: http://localhost:8083/*
  7. Save and note the Client secret
  8. Update KEYCLOAK_CLIENT_ID in your configuration

πŸ’» Usage Examples

User Registration

@Autowired
private UserService userService;

UserRegistrationRequest request = new UserRegistrationRequest(
    "john.doe@example.com",
    "password123",
    "John",
    "Doe"
);

UserResponse user = userService.registerUser(request);

User Login

LoginRequest loginRequest = new LoginRequest(
    "john.doe@example.com",
    "password123"
);

LoginResponse response = userService.login(loginRequest);
String accessToken = response.accessToken();
String refreshToken = response.refreshToken();

Get Current User

UserResponse currentUser = userService.getMe();

Assign Role

userService.assignRoleToUser(userId, "ADMIN");

πŸ› οΈ Configuration

Application Properties

spring:
  application:
    name: keycloak-security-service

keycloak:
  realm: ${KEYCLOAK_REALM:my-realm}
  auth:
    server:
      url: ${KEYCLOAK_SERVER_URL:http://localhost:8080}
  resource: ${KEYCLOAK_CLIENT_ID:springboot-security-client}
  credentials:
    secret: ${KEYCLOAK_CLIENT_SECRET:}
  admin:
    username: ${KEYCLOAK_ADMIN_USERNAME:admin}
    password: ${KEYCLOAK_ADMIN_PASSWORD:admin}
    client-id: ${KEYCLOAK_ADMIN_CLIENT_ID:admin-cli}

server:
  port: ${SERVER_PORT:8083}

Security Configuration

The library automatically configures:

  • JWT token validation
  • Role extraction from Keycloak tokens
  • Public endpoint access (login, logout, password reset)
  • Protected endpoint authentication

πŸ”’ Security Features

  • JWT Token Validation - All tokens are validated against Keycloak
  • Role-Based Access Control - Roles from Keycloak are mapped to Spring Security authorities
  • Stateless Sessions - No server-side session storage
  • CSRF Protection Disabled - Suitable for API-only applications
  • Password Reset - Secure password reset flow

πŸ“– DTOs

LoginRequest

public record LoginRequest(
    String username,
    String password
) {}

LoginResponse

public record LoginResponse(
    String accessToken,
    String refreshToken,
    String tokenType,
    Long expiresIn
) {}

UserResponse

public record UserResponse(
    String id,
    String username,
    String email,
    String firstName,
    String lastName,
    List<String> roles,
    List<String> groups
) {}

πŸ§ͺ Testing

# Run all tests
mvn test

# Run with specific profile
mvn test -Ptest

🐳 Docker Support

Docker Compose (Recommended)

See the Quick Start section above for the easiest setup.

Standalone Docker Build

Build and run the application container:

docker build -t springboot-keycloak-security .
docker run -p 8083:8083 \
  -e KEYCLOAK_SERVER_URL=http://localhost:8080 \
  -e KEYCLOAK_REALM=my-realm \
  -e KEYCLOAK_CLIENT_ID=user-management-service \
  -e KEYCLOAK_CLIENT_SECRET=your-secret \
  springboot-keycloak-security

Note: When running standalone, ensure Keycloak is accessible at the configured URL.

πŸ› Troubleshooting

Keycloak Connection Issues

Problem: Application can't connect to Keycloak

Solutions:

  • Verify Keycloak is running: curl http://localhost:8080/health/ready
  • Check KEYCLOAK_SERVER_URL in your environment variables
  • For Docker Compose, ensure services are on the same network
  • Check Keycloak logs: docker-compose logs keycloak

Client Secret Issues

Problem: Authentication fails with "Invalid client credentials"

Solutions:

  • Verify the client secret matches what's in Keycloak
  • Get the secret from: Keycloak Admin β†’ Clients β†’ [Your Client] β†’ Credentials
  • Ensure KEYCLOAK_CLIENT_ID matches the client ID in Keycloak
  • Restart the application after updating the secret

Realm Not Found

Problem: "Realm not found" errors

Solutions:

  • Verify the realm exists in Keycloak
  • Check KEYCLOAK_REALM matches the actual realm name
  • Import the realm from realm-export.json if using the provided setup

Port Conflicts

Problem: Port already in use

Solutions:

  • Change SERVER_PORT in .env for the Spring Boot app
  • Change KEYCLOAK_PORT in .env for Keycloak
  • Stop other services using those ports

Database Connection (Docker Compose)

Problem: Keycloak can't connect to PostgreSQL

Solutions:

  • Ensure PostgreSQL container is healthy: docker-compose ps
  • Check PostgreSQL logs: docker-compose logs postgres
  • Verify database credentials in .env match docker-compose.yml

πŸ“ License

This project is open source and available under the MIT License.

🀝 Contributing

Contributions are welcome! Please read our Contributing Guidelines for details on:

  • Code style and standards
  • Development setup
  • Testing requirements
  • Pull request process
  • Commit message conventions

Quick checklist:

  • βœ… All code follows Java best practices
  • βœ… Comprehensive JavaDoc is included
  • βœ… Unit tests are provided
  • βœ… Code is properly formatted
  • βœ… Documentation is updated

πŸ“š Additional Resources

Documentation Files

  • Setup Guide - Detailed step-by-step setup instructions
  • Contributing Guidelines - How to contribute to this project
  • LICENSE - MIT License details
  • .env.example - Environment variable template (create .env from this)

External Links

πŸ“§ Support

For issues and questions:

  • Open an issue on the repository
  • Check existing documentation and troubleshooting section
  • Review example configurations in .env.example
  • Check Contributing Guidelines for development help

Made with ❀️ by Teyoh

About

This reposity helps with setting up keycloak, user management and authentication with Java springboot!

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors