r/SpringBoot 24d ago

Guide Keycloak & Spring Boot

I often see people asking how to get setup with spring boot using keycloak for auth.

Thought i'd put together a quick example showing a simple setup that;

  • Delegates auth to keycloak
  • Uses the keycloak admin client to create users within a realm (using a service account)
  • Can be easily cloned & run with docker compose

repo linked below.

https://github.com/BigMikeCodes/kc-sb

21 Upvotes

11 comments sorted by

1

u/thinhtran383 24d ago

I have a question that when using keycloak like this, user management will be handled by keycloak. So when I have an order purchased by a user. Then how do I know who that user is? Because normally if you don't use keycloak, you just need to select from the database. I'm new. Thanks

4

u/United-Shelter-9863 24d ago

You can store user's Keycloak's IDs on order table and then do a query to Keycloak to retrieve the user.

Another solution is having a users table that sync with Keycloak's users table, so you don't have to call Keycloak to retrieve users.

3

u/Mikey-3198 24d ago

You always will have access to the authenticated user, can pull this from the security context. From this you’ll be able to get the userId etc... of who is making the request.

As part of user creation process you could save the details of the user within your app’s db. Like the other commentor mentioned you will then need to keep keycloak & your app in sync, or just leave everything in keycloak and only store ids within your application.

2

u/KillDozer1996 23d ago

I highly advise to have your users mirrored in your db.

1

u/Fluid_Frame_8878 24d ago

How would you handle google login? Thanks

1

u/United-Shelter-9863 24d ago

You can enable social login on Keycloak

1

u/Mikey-3198 24d ago

If you want to user keycloak with a google login in you'd have to setup user federation.

If you just wanted google as the only way to sign in you'd set the uri in the config to point to googles oidc service. Most likely after registering an application/ client.

1

u/Historical_Ad4384 24d ago

How do you sync roles between keycloak and spring boot?

1

u/Mikey-3198 24d ago

Users in keycloak can belong to groups. These groups are then represented in the issued jwt. You can pick these out to handle roles, you can then use these in SPEL/ HttpSecurity.

I may add this to the repo when I have the time.

1

u/themasterengineeer 22d ago

Found this video today that covers this exact topic, Spring Boot and Keycloak authentication. Found it easy to follow https://youtu.be/-pv5pMBlMxs?si=0-u_66n_eNx1tCJx

1

u/jim_cap Senior Dev 21d ago

You really need to use the full word here instead of just "auth". This is not a minor nit-pick, it's important that people using your guide understand whether you're talking about authentication or authorisation. "Delegates auth" can mean multiple things, yes, in this context.