Using Keycloak with Spring Boot: Full Identity Provider Integration
If you’re building a modern enterprise-grade application, identity management is no longer an optional extra—it’s foundational. Whether you’re aiming for single sign-on (SSO), managing fine-grained access control, or just tired of implementing login logic for the hundredth time, Keycloak is probably already on your radar.
But what happens when you combine the powerful identity provider capabilities of Keycloak with the elegance of Spring Boot? A bit of magic, if done right. In this article, we’ll walk through that integration—from defining realms and clients to implementing token exchange and SSO. We’ll also touch on gotchas that you’ll likely run into and how to avoid them.
1. Why Keycloak?
Before jumping into the how, let’s set the stage.
Keycloak is an open-source identity and access management solution developed originally by Red Hat and now stewarded by the Keycloak community. It offers out-of-the-box features like:
- Single sign-on (SSO)
- LDAP integration
- OAuth2/OpenID Connect support
- Multi-tenancy via realms
- Token exchange and identity brokering
It’s built on standards (OIDC, SAML, OAuth2) and works beautifully with Spring Boot through its support for OAuth2 clients.
As @springboot put it in one tweet:
“Security doesn’t have to be a nightmare. With Spring Security and Keycloak, it can be seamless and even enjoyable.” – @springboot
2. Understanding the SSO Flow: How Keycloak Integrates with Multiple Spring Boot Apps
After the user accesses the Spring Boot application, they are redirected to Keycloak for authentication. Once logged in, the access token is sent back and used to access protected resources. This same flow applies across applications, making SSO seamless. The diagram below illustrates this entire process in detail:
3. Realms: Multi-Tenancy Made Simple
A realm in Keycloak is like a tenant. It’s an isolated set of users, credentials, roles, and clients. This means you can create one realm for your customers, one for internal apps, and one for your partners—each with different login flows, identity providers, and role mappings.
Say you’re building a B2B SaaS platform. You want each client company to have its own user directory. With Keycloak, that’s as easy as creating a realm per company.
When setting up realms:
- Go to Keycloak Admin Console
- Create a new realm (
example-realm) - Add a client (e.g.,
springboot-client) withconfidentialaccess type and setValid Redirect URIstohttp://localhost:8080/*
This defines the application that will use Keycloak for authentication.
4. Spring Boot Integration (Code Time)
First, add the necessary dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
Then configure your application.yml:
spring:
security:
oauth2:
client:
registration:
keycloak:
client-id: springboot-client
client-secret: YOUR_SECRET
provider: keycloak
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
provider:
keycloak:
issuer-uri: http://localhost:8080/realms/example-realm
And in your controller, you can now access the user’s identity:
@GetMapping("/me")
public String me(@AuthenticationPrincipal OidcUser user) {
return "Hello, " + user.getFullName();
}
Boom. Your Spring Boot app is now talking to Keycloak. You can log in via Keycloak’s login UI, and Spring Boot handles the session and authentication context.
5. Single Sign-On: One Login to Rule Them All
Single sign-on across multiple Spring Boot apps is where Keycloak shines.
All you need to do is:
- Point both apps to the same realm
- Use the same identity provider
- Configure the same client or set of clients
Once a user logs in via one app, accessing the second app will redirect them to Keycloak—but since they’re already authenticated, Keycloak immediately redirects back with a token. Seamless.
In practical terms, it feels like magic.
Here’s a thread where a user ran into an SSO issue and solved it by tweaking the realm session settings:
👉 @joekoda_dev
“Lesson learned: Keycloak SSO doesn’t ‘just work’ if your clients have wildly different session settings. Align those first!”
To test this locally:
- Run two apps on different ports (e.g.,
8080and8081) - Use the same realm and client config
- Enable “SSO Session Idle” to 30 minutes in the realm settings
6. Token Exchange: Role Switching Without Re-authentication
Let’s say your backend service wants to act on behalf of a user. Or maybe you want a backend-to-backend token handoff without forcing the user to log in again. Enter token exchange.
Keycloak allows a client to exchange its access token for another one—potentially with a different scope, audience, or even representing another user.
Enable token exchange in Keycloak:
- Go to Clients →
springboot-client - Add a client scope
- Enable “Direct Access Grants”
- Grant the “Token Exchange” client role
Now call Keycloak’s token exchange endpoint:
curl -X POST http://localhost:8080/realms/example-realm/protocol/openid-connect/token \ -d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \ -d "client_id=springboot-client" \ -d "client_secret=YOUR_SECRET" \ -d "subject_token=USER_ACCESS_TOKEN" \ -d "requested_token_type=urn:ietf:params:oauth:token-type:access_token"
This returns a new access token scoped to your requested audience. Very useful when chaining service calls or impersonating users for support/debugging flows.
7. Debugging Tips & Gotchas
- If login fails silently, check your Valid Redirect URIs and Web Origins in the Keycloak client settings.
- When using Spring Security filters, always check the order—Keycloak’s filter must come before the default security filters.
- Keycloak refresh tokens aren’t infinite. You need to implement token refresh logic or use Spring’s built-in session timeout handling.
Also, if you’re deploying this behind a reverse proxy (e.g., NGINX or Kubernetes Ingress), ensure that forwarded headers are handled correctly—otherwise redirect URIs break.
8. Final Thoughts
Keycloak and Spring Boot together provide one of the cleanest, most robust authentication solutions available in the open-source world today. Whether you’re building a simple login page or a full SSO experience across dozens of apps, the integration is surprisingly painless—once you get the hang of the realm-client-token trifecta.
But don’t stop at “it works.” Master the flows. Know your realms. Test token lifetimes. Understand how SSO works behind the scenes. You’ll thank yourself later.
As @prabindh_ once tweeted:
“Keycloak taught me more about OAuth2 than any spec ever did. You break it, you learn it.”
🔗 https://twitter.com/prabindh_/status/1330245587791749121
9. References and Docs
- 🔒 Keycloak Docs: Token Exchange
- 📘 Spring Security OAuth2 Docs
- 🎯 Keycloak Realms Explained
- 💡 Example GitHub Repo: Spring Boot + Keycloak
- 🐦 Tweet by @springboot on OAuth2 magic
- 🐛 Troubleshooting SSO with Keycloak – Twitter Thread





