Skip to content

Latest commit

 

History

History
258 lines (203 loc) · 7.88 KB

File metadata and controls

258 lines (203 loc) · 7.88 KB

Keycloak Spring Boot Authentication Microservice

A complete Spring Boot microservice demonstrating Keycloak integration for authentication and authorization with role-based access control, user management, and password reset functionality.

🚀 Features

  • 🔐 Authentication & Authorization: Role-based access control with Keycloak
  • 👥 User Management: Create, login, and manage users programmatically
  • 🔄 Password Reset: Secure email-based password reset with JWT tokens
  • 📧 Email Integration: SMTP email service for notifications
  • 🐳 Docker Support: Complete Keycloak setup with MariaDB
  • 🛡️ Security: OAuth2 Resource Server with JWT validation

🏗️ Architecture

This project demonstrates:

  1. How to guard endpoints with @RolesAllowed & path prefix
  2. Create users with Spring Boot
  3. Login users and get access tokens with Spring Boot
  4. Implement secure password reset functionality

📋 Prerequisites

  • Java 11 or higher
  • Maven 3.6+
  • Docker and Docker Compose
  • MySQL/MariaDB (if not using Docker)

🛠️ Installation & Setup

1. Clone the Repository

git clone https://github.com/devpayoub/Keycloak-with-Spring-Boot-Authentication-System.git
cd Keycloak-with-Spring-Boot-Authentication-System

2. Start Keycloak with Docker

cd src/main/resources
docker-compose up -d

This will start:

  • Keycloak server on port 18080
  • MariaDB database for Keycloak

3. Import Keycloak Realm

  1. Access Keycloak admin console: http://localhost:18080
  2. Login with admin credentials (check keycloak.env file)
  3. Import the realm from import-this-realm.json

4. Configure Application Properties

Create application.properties file in src/main/resources/ with the following configuration:

# Application Configuration
spring.application.name=test
server.port=8081

# Keycloak Configuration
keycloak.realm=think-auth
keycloak.auth-server-url=http://localhost:8080
keycloak.ssl-required=external
keycloak.resource=oauth2
keycloak.public-client=true
keycloak.confidential-port=0

# OAuth2 Resource Server Configuration
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/realms/think-auth

# Keycloak Client Secret (replace with your actual client secret)
keycloak.credentials.secret=YOUR_CLIENT_SECRET_HERE
keycloak.use-resource-role-mappings=false
keycloak.bearer-only=true
logging.level.org.springframework.security=DEBUG
logging.level.org.keycloak=DEBUG

# MySQL Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/keycloak_1
spring.datasource.username=YOUR_DB_USERNAME
spring.datasource.password=YOUR_DB_PASSWORD
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Email Configuration
spring.mail.host=YOUR_SMTP_HOST
spring.mail.port=465
spring.mail.username=YOUR_EMAIL_USERNAME
spring.mail.password=YOUR_EMAIL_PASSWORD
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true

5. Build and Run

mvn clean install
mvn spring-boot:run

The application will start on http://localhost:8081

🔧 Configuration Variables

Required Environment Variables

Variable Description Example
keycloak.realm Keycloak realm name think-auth
keycloak.auth-server-url Keycloak server URL http://localhost:8080
keycloak.resource Keycloak client ID oauth2
keycloak.credentials.secret Keycloak client secret your-client-secret
spring.datasource.url Database connection URL jdbc:mysql://localhost:3306/keycloak_1
spring.datasource.username Database username root
spring.datasource.password Database password your-db-password
spring.mail.host SMTP server host smtp.gmail.com
spring.mail.username Email username your-email@gmail.com
spring.mail.password Email password your-email-password

📡 API Endpoints

Public Endpoints

  • GET /public/hello - Public greeting message

Protected Endpoints

  • GET /member/hello - Requires MEMBER role
  • GET /moderator/hello - Requires MODERATOR role
  • GET /admin/hello - Requires ADMIN role

User Management

  • POST /user/create - Create new user
  • POST /user/login - User login
  • POST /user/forgot-password - Request password reset
  • POST /user/reset-password - Reset password with token

🔐 Authentication Flow

  1. User Registration: Admin creates user via /user/create
  2. User Login: User authenticates via /user/login
  3. Token Validation: JWT tokens are validated for protected endpoints
  4. Role-based Access: Endpoints are protected based on user roles

🗄️ Database Setup

The project uses MySQL/MariaDB for Keycloak data storage. When using Docker Compose, the database is automatically configured.

For manual setup:

  1. Create database: keycloak_1
  2. Update database credentials in application.properties
  3. Keycloak will create necessary tables automatically

📧 Email Configuration

The application supports email notifications for password reset. Configure your SMTP settings in application.properties:

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-app-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

🐳 Docker Support

The project includes Docker Compose configuration for easy Keycloak setup:

version: '3'
services:
  keycloak:
    image: jboss/keycloak:15.0.2
    ports:
      - "18080:8080"
    depends_on:
      - keycloak_db
  keycloak_db:
    image: mariadb:10.3.26

🔒 Security Features

  • OAuth2 Resource Server: JWT token validation
  • Role-based Access Control: Fine-grained authorization
  • Password Reset: Secure token-based password reset
  • Email Verification: User email verification support
  • CSRF Protection: Configurable CSRF protection

🧪 Testing

Test User Creation

curl -X POST http://localhost:8081/user/create \
  -H "Content-Type: application/json" \
  -d '{
    "firstname": "John",
    "lastname": "Doe",
    "email": "john.doe@example.com",
    "password": "password123"
  }'

Test Login

curl -X POST http://localhost:8081/user/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john.doe@example.com",
    "password": "password123"
  }'

Test Protected Endpoint

curl -X GET http://localhost:8081/member/hello \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

📁 Project Structure

src/main/java/com/oauth/keycloak/springbootauth/
├── controller/          # REST API endpoints
│   ├── HelloController.java
│   └── UserController.java
├── service/            # Business logic
│   ├── KeycloakAdminClientService.java
│   └── TokenService.java
├── config/             # Configuration classes
│   ├── KeycloakSecurityConfig.java
│   ├── KeycloakProvider.java
│   └── KeycloakResolverConfig.java
└── http/               # Request/Response models
    └── requests/

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Commit your changes
  4. Push to the branch
  5. Create a Pull Request

🔗 References

⚠️ Important Notes

  • Never commit sensitive information like passwords, API keys, or database credentials
  • Use environment variables or external configuration for production deployments
  • The application.properties file is excluded from version control for security reasons
  • Always use HTTPS in production environments