
Introduction
Modern applications require strong authentication and authorization. Instead of managing passwords and user sessions manually, developers increasingly rely on identity providers like Keycloak. Combined with Spring Boot and OAuth2, Keycloak makes securing APIs and web apps much easier. In this post, you’ll learn how OAuth2 works in Spring Boot, how Keycloak fits into the picture, and how to integrate both to protect your services.
What Is OAuth2?
OAuth2 is an industry-standard protocol for authorization. It allows applications to delegate authentication to an identity provider and receive access tokens that represent user identity and permissions. As a result, your backend doesn’t need to handle passwords directly.
Key Components
- Authorization Server: Issues tokens (Keycloak).
- Resource Server: Your Spring Boot API that validates tokens.
- Client Application: Web or mobile app that requests tokens.
- Access Token: A signed token that grants access to protected resources.
This separation improves security and keeps your application architecture clean.
Why Use Keycloak?
Keycloak is an open-source identity and access management solution. It supports OAuth2, OpenID Connect, social logins, user federation, and more. Because it’s open-source, flexible, and easy to run, many teams choose it as their OAuth2 provider.
Key Features
- Single sign-on (SSO)
- Token management
- Built-in admin dashboard
- Role-based access control
- Integration with Spring Security
Therefore, Keycloak becomes a strong authentication layer for both microservices and monolithic apps.
Setting Up Keycloak
Start Keycloak using Docker:
docker run -p 8080:8080 quay.io/keycloak/keycloak:latest start-dev
Then open the admin console at:
http://localhost:8080
Create a realm, client, and roles. Next, configure a client for your Spring Boot app and enable “confidential” or “public” access types depending on your needs.
Adding OAuth2 to Spring Boot
Add the following dependencies to your project:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
Configure Your Application
Add basic OAuth2 resource server settings:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:8080/realms/myrealm
This tells Spring Boot to expect JWT tokens from your Keycloak realm.
Protecting API Endpoints
Use Spring Security to restrict access:
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public").permitAll()
.requestMatchers("/admin").hasRole("admin")
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt());
return http.build();
}
}
This setup ensures only authenticated users can access protected routes.
Using Roles and Claims
Keycloak allows you to define user roles and custom claims. After assigning roles inside your realm, Spring Security automatically maps them to authorities inside the JWT token.
Example JWT snippet:
{
"realm_access": {
"roles": ["admin", "user"]
}
}
Consequently, your application can enforce fine-grained permissions based on these claims.
Logging In from a Frontend
If you have a frontend (React, Angular, Vue), you can redirect users to Keycloak’s login page. After successful login, Keycloak returns the user with an access token and refresh token.
Popular approaches include:
- OAuth2 Authorization Code Flow
- Using Keycloak’s official JavaScript SDK
- Using frontend libraries like
react-keycloak
These tools simplify token storage, refresh handling, and logout flows.
Refresh Tokens and Session Management
Spring Boot validates tokens locally, which makes every request fast. Keycloak handles user sessions, token expiration, and refresh tokens. Because of this separation, you gain strong security without adding complexity to your backend.
Best Practices
- Always validate tokens using the issuer URI.
- Enable HTTPS in production.
- Use short-lived access tokens.
- Assign roles through Keycloak, not hardcoded in your app.
- Rotate signing keys regularly.
Following these steps keeps your identity layer reliable and secure.
Final Thoughts
Securing applications with Spring Boot, OAuth2, and Keycloak provides a powerful and scalable authentication setup. It reduces the need to manage passwords, simplifies token validation, and gives you full control over roles and permissions. Start by setting up a realm and connecting your Spring Boot API, then expand into securing your frontend and defining advanced policies. To continue learning about Spring security patterns, read API Routing with Spring Cloud Gateway. For detailed configuration steps, explore the Keycloak documentation.