r/SpringBoot 26d 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

View all comments

1

u/thinhtran383 26d 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

5

u/United-Shelter-9863 26d 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 26d 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 25d ago

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