This post has been featured in the 7th anniversary edition of This Week in Spring – January 2n, 2018.
Here’s a short post how to authenticate against Keycloak from within a Spring Boot 2 application. For Spring Boot 1.5.x there’s a community adapter from the Keycloak-team that takes the burden from you, but this adapter is not yet ready for Spring Boot 2 and Spring Security 5.
I had the following requirements for the setup I am gonna present:
- Manage users outside one application (i.e. be ready for a bunch of services): Realized with Keycloak
- Full integration with Spring Security, especially method security
- Funktional with server side rendered Thymeleaf or other template systems supported by Spring Boot
Here is the fully functional demo project: keycloakdemo. I am not replicating some comments from the sources in the following paragraphs.
With Spring Boot 2 comes Spring Security 5 and the first class support for OAuth Login: New feature OAuth2-Login. That means one doesn’t need separate modules anymore. But to make this work, it’s not enough to have
spring-boot-starter-security on the class path, you’ll need two more dependencies:
I’ll spare you the details on how to setup Keycloak and how to create a realm and what a realm is. Keycloak has an excellent documentation about that and the screenshots from the one existing tutorial on how to use the Spring Boot adapter have been copied around anyway, along with that post.
Next step, prepare your application and disable Security-Autoconfiguration completely. Right now, it doesn’t stop generating a default user and I don’t want that when I connect the application to an external user database.
Note: There’s an issue about the default user when using OAuth-login: #10531.
I have introduced a simple property-component to store all (for my use case) relevant Keycloak configuration elements. Should fit a standard use case in most times, too. All this stuff can be configured through new Spring Boot Properties for Security 5 as well (as described in there in the documentation), but those aren’t even fun for people who like YAML, not speaking of me, the last
.properties-fan out there.
So these properties here
maps neatly to:
Read more about the client registration here. The instance of
ClientRegistration generated from the properties here is put to use in my security configuration, the core of this tutorial:
It all boils down to the registered clients through the bean
clientRegistrationRepository and then in
oauth2Login in the security configurer. The following controller together with a simple Thymeleaf template is just for demoing purposes:
Assuming you have a Keycloak server running on port 8080, you can checkout the above linked project, build it with Java 9 and run it on port 8082. Open http://localhost:8082, hit login and you should be redirected to your Keycloak instance and back after a successful login.
Needless to say that this setup works well with other OAuth 2 providers.