Simplifying Authentication and Authorization in Spring Boot with Keycloak

When building modern web applications, managing user authentication and authorization can get complex and time-consuming. That’s where Keycloak comes in — a powerful open-source identity and access management solution that integrates seamlessly with Spring Boot.

What is Keycloak?

Keycloak is an open-source Identity and Access Management (IAM) tool developed by Red Hat. It provides:

  • • Single Sign-On (SSO)
  • • User federation (LDAP, Active Directory)
  • • Social login (Google, GitHub, Facebook)
  • • Multifactor authentication
  • • OAuth2 / OpenID Connect / SAML support
  • • Centralized user & role management

With Keycloak, developers can offload the heavy lifting of user management and security, focusing more on application logic.

Common Use Cases

  • • Secure REST APIs and web apps
  • • SSO across microservices
  • • Role-based access control (RBAC)
  • • External login provider support (Google, Azure AD, etc.)
  • • Identity federation for enterprise apps

Setting Up Keycloak

Running Keycloak Locally

There are multiple ways to run Keycloak locally. The easiest and most flexible way for developers is using Docker.

Option 1: Using Docker (Recommended)

docker run -p 8080:8080 \
-e KEYCLOAK_ADMIN=admin \
-e KEYCLOAK_ADMIN_PASSWORD=admin \
quay.io/keycloak/keycloak:25.0.3 \
start-dev

After starting, access the Keycloak admin console at: http://localhost:8080

Option 2: Using Local Scripts

1. Download Keycloak: Click here

2. Extract and run

./kc.sh start-dev --admin admin --password admin

3. Access the admin console at: http://localhost:8080

Other Setup Options

Keycloak supports Kubernetes, Podman, and production deployments via HTTPS and external databases. Explore more: Keycloak Getting Started

Keycloak Admin Console Basic Configuration

  1. Create a Realm:
    • → Go to Realms > Create Realm
    • → Name it demo-realm and save
  2. Create a Client:
    • → Go to Clients > Create Client
    • → Client ID: spring-boot-client
    • → Protocol: openid-connect
    • → Access Type: confidential
    • → Valid Redirect URIs: http://localhost:8081/*
    • → Web Origins: +
    • → Save and copy the client secret from the Credentials tab
  3. Create Roles:
    • → Go to Roles > Add Role
    • → Add roles like ROLE_USER and ROLE_ADMIN
  4. Create Users:
    • → Go to Users > Add User
    • → Set username, email, and other info > Save
    • → Go to Credentials, set a password, and turn off temporary status > Save
    • → Go to Role Mappings tab > Assign appropriate roles to the user

Running Keycloak in Production

For production environments, follow these best practices:

  • • Use HTTPS (self-signed or reverse proxy like NGINX)
  • • Use a production-grade database (PostgreSQL, MySQL)
  • • Enable clustering for high availability
  • • Configure token lifespans and session timeouts
  • • Secure and isolate the admin console
  • • Use realm exports and Keycloak Admin CLI (kcadm.sh) for automation and version control

You can also use docker-compose to manage production-like local environments. It’s ideal for simulating multi-service architectures.

version: '3.8'
services:
keycloak:
image: quay.io/keycloak/keycloak:25.0.3
ports:
- "8080:8080"
environment:
- KEYCLOAK_ADMIN=admin
- KEYCLOAK_ADMIN_PASSWORD=admin
command: start-dev

Spring Boot Integration Example

Let’s build a Spring Boot Book Management System that uses Keycloak for authentication and role-based access.

Add Maven Dependencies

<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
<version>25.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

Add properties

application.properties

server.port=8081

keycloak.auth-server-url=http://localhost:8080
keycloak.realm=demo-realm
keycloak.resource=spring-boot-client
keycloak.credentials.secret=YOUR_CLIENT_SECRET
keycloak.ssl-required=none
keycloak.use-resource-role-mappings=true

spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/realms/demo-realm
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:8080/realms/demo-realm/protocol/openid-connect/certs

Spring Security Configuration

@EnableWebSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/books/admin/**").hasRole("ADMIN")
.requestMatchers("/books/user/**").hasRole("USER")
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt());

return http.build();
}
}

Book Controller Example

@RestController
@RequestMapping("/books")
public class BookController {

@GetMapping("/user/list")
public ResponseEntity<String> userBooks() {
return ResponseEntity.ok("Books available for USER role.");
}

@GetMapping("/admin/list")
public ResponseEntity<String> adminBooks() {
return ResponseEntity.ok("Books available for ADMIN role.");
}
}

Admin Console Settings

  • • Assign Roles in Keycloak:
    → Go to Users → Select a user → Role Mappings, and assign roles (ROLE_USER, ROLE_ADMIN). → These roles control access to your Spring Boot endpoints.
  • • Other Key Features:
    → Manage and configure realms, roles, users, sessions, login flows, event logs, identity providers, and security policies. The admin console also allows integration with external directories (LDAP/AD) and supports enabling two-factor authentication.

Admin Console is intuitive, supports debugging, monitoring, and secure configuration for authentication flows

Extending Keycloak Integration in Spring Boot

Here are more things you can do with Keycloak:

Fine-Grained Authorization

  • • Use @PreAuthorize(“hasRole(‘ADMIN’)”) for method-level access control.
  • • Map Keycloak roles to your own domain model using custom mappers.

Custom Login Flows

  • • Use Keycloak’s theming support to customize login pages.
  • • Enable 2FA (two-factor authentication) for sensitive apps.

Admin APIs

  • • Use Keycloak’s Admin REST API to manage users, roles, and groups programmatically.

Frontend Integration

Use OpenID Connect to secure SPA apps (React, Angular) and have SSO with your Spring Boot backend.

coma

Conclusion

Keycloak offers a powerful, flexible, and production-ready solution for authentication and authorization in modern applications. With minimal configuration, you can secure your Spring Boot apps, manage roles, and integrate external identity providers — all from a central admin interface.

Don’t reinvent the wheel. Let Keycloak handle your user management so you can focus on building your application.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?