Use Keycloak with your Spring Boot 2 application

Facilitate Spring Security 5 OAuth login to authenticate against Keycloak
December 28, 2017 by Michael

This post has been featured in the 7th anniversary edition of This Week in Spring – January 2n, 2018.

Important updates on March 22nd, 2018: Thanks to valid feedback from friends and colleagues Stéphane and Jochen and in the light of the high interested in this post, I have updated the demo. I basically removed all the boilerplate. With Spring Boot 2 final and Spring Security 5 final, you can use OAuth2 login from within a Boot-application agains Keycloak without the need of a key cloak starker or any boilerplate code. All you need is a sane configuration. Due to the nesting of the needed properties, I switched to YAML.

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. The realm I used in the demo is part of the repo: test-realm.json. It’s easy to import into Keycloak.

Next step, prepare your application as usual, that is: Annotate your Main-class with @SpringBootApplication. Then configure your client registration together with Keycloak as the provider for the client as described in there in the documentation:

The first two properties are reused in the registration below so that I don’t have to copy them all over the place. This configuration creates a client registration for you. If you need more control, the documentation is there to help you: About client registration.

And now you’re ready to configure your security as usual with the added, new option .oauth2Login().

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.

14 comments

  1. kotychok wrote:

    Hello. Thanks for the interesting post.
    Could I tell you how to use it correctly to RestController. And how to make a logout.
    Thank you.

    Posted on February 20, 2018 at 3:35 PM | Permalink
  2. Michael wrote:

    There’s an example how to use a @PreAuthorize annotation in a rest controller directly at the bottom.

    You can also use @RolesAllowed etc.

    Those are Spring Security 101 and I highly recommend to get your self acquainted with those.

    Posted on February 21, 2018 at 6:33 PM | Permalink
  3. Salam wrote:

    Hi,

    Thanks for the article. Could you describe how can we logout the user with OAuth and KeyCloak?

    Thanks

    Posted on February 26, 2018 at 3:01 PM | Permalink
  4. Michael wrote:

    Hi,
    as there is no session – at least when you didn’t explicitly configure one – you have to delete the JWT-token that authorizes you on the client side (i.e. delete the JWT cookie).

    Posted on February 27, 2018 at 7:47 AM | Permalink
  5. Salam wrote:

    Well, that’s what I thought at first, but it does not work.

    I cleared all cache and cookies from the browser dev tools (I am using Chrome, FYI), but the problem is that the server somehow still knows that I am authenticated. Its weird and I do now know how can that be but you can easily reproduce it. 🙁

    Also, I don’t see a JWT token but rather a JSESSIONID and SESSION cookies.

    I also tried changing the line where is says –
    .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
    to different values without any help. STATELESS doesnt even work.

    Posted on February 27, 2018 at 11:59 AM | Permalink
  6. Basil wrote:

    Hi Michael,

    Thanks for putting together a great article.

    I checked out your project and did a mvn clean install and got the following error:

    [INFO] ————————————————————————
    [INFO] BUILD FAILURE
    [INFO] ————————————————————————
    [INFO] Total time: 18.247 s
    [INFO] Finished at: 2018-02-27T09:23:21-07:00
    [INFO] Final Memory: 29M/97M
    [INFO] ————————————————————————
    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project keycloakdemo: Compilation failure: Compilation failure:
    [ERROR] /Users/basil/DEVELOPMENT/michealsimons/keycloakdemo/src/main/java/ac/simons/keycloakdemo/DemoApplication.java:[21,55] cannot find symbol
    [ERROR] symbol: class SecurityAutoConfiguration
    [ERROR] location: package org.springframework.boot.autoconfigure.security
    [ERROR] /Users/basil/DEVELOPMENT/michealsimons/keycloakdemo/src/main/java/ac/simons/keycloakdemo/DemoApplication.java:[53,34] cannot find symbol
    [ERROR] symbol: class SecurityAutoConfiguration
    [ERROR] -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/conflu.....eException

    Posted on February 27, 2018 at 5:46 PM | Permalink
  7. Michael wrote:

    Thanks a lot for that comment, Basil!
    That must have been a recent change in the Spring Boot 2 Build-Snapshot.

    I’ve fixed it: https://github.com/michael-simons/keycloakdemo/commit/5dcf261d527693fbf7fec1bb8bc5ba05984cec33

    Posted on February 27, 2018 at 9:43 PM | Permalink
  8. Allahbaksh wrote:

    Can you also commit the keycloak.json file to configure easily.

    Posted on March 2, 2018 at 6:59 PM | Permalink
  9. Michael wrote:

    Do you mean exporting the realm?

    Posted on March 2, 2018 at 8:03 PM | Permalink
  10. Allahbaksh wrote:

    Yes you can commit the realm. So it is easy to configure for folks and to test what works and what does not.

    Posted on March 3, 2018 at 7:38 AM | Permalink
  11. SnuK wrote:

    Will this work with the Spring boot 2.0 release?

    Posted on March 14, 2018 at 5:47 AM | Permalink
  12. hantsy wrote:

    HI, I have tried to get oauth2 support with Spring Security 5, but I can not find where to get the **client secrect**?

    Posted on March 18, 2018 at 8:12 AM | Permalink
  13. Michael wrote:

    Hantsy: The client secret is displayed in the Keycloak-admin page. You have to set “Access Type” of your realm to confidential.

    Posted on March 22, 2018 at 7:22 PM | Permalink
  14. Michael wrote:

    I’ve updated my post and simplified the demo a lot. Also included now is the realm I’m using.

    Posted on March 22, 2018 at 7:52 PM | Permalink
Post a Comment

Your email is never published nor shared. Required fields are marked *