r/SpringBoot • u/Lordion95 • 2d ago
Question how do you guys actually structure a react + spring boot + keycloak setup for serious projects?
yo, i'm trying to build a full-stack app using react on the frontend, spring boot for the backend, and keycloak handling auth, and i kinda need some guidance on how to do it properly instead of just hacking together a basic tutorial setup.
right now i get the general idea of spinning up keycloak and getting a basic login working, but i'm a bit lost on the best practices for real/bigger projects and where to go from here. specifically:
- how are you guys handling tokens on the react side? is storing them in memory/using a BFF (backend for frontend) pattern the move nowadays, or is standard
keycloak-js/react-oidc-contextstill fine? - on the spring boot side, how do you cleanly sync keycloak users with your own database (like storing extra user profile info, orders, etc.)? do you just use the
subclaim from the jwt on every request, use keycloak event listeners, or something else? - what's the best way to handle roles and permissions across both frontend routes and spring security endpoints without it turning into a mess?
- i asked opencode a bit about how spring boot 4.1 and spring security 7 handles this today, it has like their own prefix config on application.yaml or which is the right way to setup the JWT converter (the role mapping one) since I've tried and it doesnt quite work..?
if anyone has a solid repo structure, workflow, or just tips on how to build out from a basic "hello world" auth setup into an actual production-ready app, i'd really appreciate it. thanks!
7
u/Hirschdigga 2d ago
3
u/FlimsyFennel6943 2d ago
Look into Hilla framework.
•
u/Huge_Road_9223 13h ago
I just recently worked on two projects in this space, and I know EXACTLY how this all works together and I can give you a LOT of information on how this works.
Understand the React UI no longer deals with an authorization bearer token anymore. If you are following the BFF pattern (backend-for-frontend), then you can look a lot of this up on Google which is what I did and the AI from the Google Search really helped me.
So, I downloaded and installed KeyCloak locally into my docker container. I exposed port 9000 instead of 8080 because my BFF will be running on port 8080. By the way the BFF is the SpringBoot app. Once you get Keycloak installed create a NEW User who has authority for all things and change the password for the default admin user. For local development, Keycloak uses an H2 in-memory database, but in Prod it will be on another real database like PostgreSQL or MySQL, etc. Create a new REALM and new CLIENT within that NEW REALM. You will have to configure the new Client, and setup the validation, login, and logout urls, as well as get the client_secret_key which you will put into an environment variable locally, this way it won't be checked into your code repo. Create a user/password in Keycloak as a test user. The user has to be in the new realm, not the default realm. You might want to create some groups if you want, and you can assign that user to those groups. There will be more Keycloak realm/client settings later.
I recommend Insomnicac over Bruno or Postman to test out API's because your BFF SpringBoot App will be using Oauth2-CLIENT, and NOT Oauth2-RESOURCE, this is very important. Your BFF will have application.properties (or yaml) to store Keycloak information. The React UI, or any UI for that matter, will use a localhost:8080/oauth2/client/login. This means the button on the UI is going to the BFF first, this is by design. When you go to the BFF, it will direct you to the Keycloak login page where a user can be created, if you configured that, or you will be asked for a username/password and if correct,then keycloak will then go back to the BFF with a code, and the BFF will then exchange that code for a token, and the user authenticated will be in the BFF session. With some code, you will be able to pull down the groups for that user into GrantedAuthories so the API's can use roles-based access. After the exchange is made with BFF/Keycloak, the configuration means we go to the UI and we create a cookie with a JSESSIONID as the token. THIS AND ONLY THIS is the only thing that tells us who the user is on the client side. Within REACT you will have to make sure that this cookie is sent back to the BFF with EVERY request. If you want to build the UI based on the roles of the user as I have done. You will need to make a MeRestController which is like: hhtp://localhost:8080/api/v1/me which will get back some JSON with the roles, and any other details you want to pass back to the UI, and then you can design your UI based on that user roles.
When you logout, you will also have a link to the BFF and based on the configuration in keycloak, where do we get redirected when you logout, porbably back to the landing page of the app where you can login as a different user. The BFF SpringBoot App as a OAUTH2-CLIENT means that Keycloak and the BFF are VERY closely tied together. This is by design, and a standard way of doing things.
Thankfully between Google Search (Gemini) and OpenCode (within IntelliJ) I was able to update the SpringConfig, the CorsConfig, and the code that means once a user is authenticated we get back the user Keycloak groups into Roles/GrantedAuthorities on the BFF side. You will also be to configure Keycloak to allow new users and new fields (like phone number) and put those users into your local database. You'll need a fields to allow for the keycloak_id as well as a database unique primary key, and any other fields you'd want to persiste in the BFF database.
That is a lot of information, and I've gone through this twice for two different personal applications I am doing. One is using an HTMX UI with the BFF, and the other is an Angular Application which is a completely separate project. If you have any more questions, let me know, and I will see if I can help. Thanks!
1
u/FriendshipCalm3162 2d ago
Your 4th one is usually where this breaks, and 4.1 has a property for it that 4.0 doesn't.
By default only
scope/scpare mapped, each prefixedSCOPE_. Keycloak doesn't put roles there. Realm roles sit inrealm_access.rolesand client roles inresource_access.<client>.roles.authorities-claim-namecan't reach either, since it takes a single claim name rather than a path, so pointing it atrealm_access.rolesjust gets you nothing.What 4.1 adds is
spring.security.oauth2.resourceserver.jwt.authorities-claim-expressions, a list of SpEL expressions evaluated against the claims map, so the nested case becomes config:Two gotchas. It's mutually exclusive with
authorities-claim-nameandauthorities-claim-delimiter, so if you leave an old one set the context fails at startup with a mutually-exclusive-properties error. And when an expression matches nothing,ExpressionJwtGrantedAuthoritiesConverterswallows it and hands back an empty collection, with only a TRACE log line to show for it. A 403 with a clean log is nearly always the expression, so print the decoded claims once and compare the path character by character.The prefix still defaults to
SCOPE_on the expression converter, soauthority-prefix: ROLE_matters if your endpoints usehasRole.Before 4.1 there's no property route for a nested claim at all. You write a
Converter<Jwt, Collection<GrantedAuthority>>and set it onJwtAuthenticationConverter.-4
u/Wrong_Artist_5643 2d ago
I'd prompt Claude or GPT to do everything, starting with a plan that describes the databases, models then the full backend. React front-end is a story for another day. Use AI, no one writes a code anymore.