Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to secure angular/spring app with keycloak?

I have a spring boot (backend) & angular (frontend) app that I'd like to secure with keycloak (for the authentication).

I have a very basic deployment, in which the executable jar created by spring also serves the client code (from angular).

I have seen several tutorials where the front and back are separated, and the front uses the code flow + pkce to delegate its authentication to keycloak, while the back is stateless and checks for presence of a jwt token certified by the keycloak instance.

However since I have a backend server, I'd like to avoid using a public client and instead rely on the back-channel token exchange on the server side. So the front should not have any knowledge of the keycloak instance.

Is that possible / is it a best practice ? Is there a front library that helps me to achieve that ? I've come across the library keycloak-angular, but it seems to be directed towards the first case, where the SPA connects directly to Keycloak instead of using a backend server.

like image 535
teresy Avatar asked Apr 26 '26 15:04

teresy


1 Answers

In such a case you don't need a frontend library. In your frontend you should just handle user session (have a session cookie) and send the cookie every time to your backend. Then the backend server should use any oauth client to communicate with your keycloak server, and once it gets the tokens it can save them in a db together with a handle to your session.

Here's how this flow might look like:

  1. request client -> backend server -> reply with a 302 to the keycloak authorization endpoint. Registered redirect_uri should be a uri exposed by the backend server
  2. user performs authentication / consent, etc.
  3. Keycloak redirects to redirect_uri with code
  4. Backend receives code (as it listens on the redirect uri address), and exchanges it with Keycloak.
  5. Backend receives access token and saves it in a DB together with session ID.
  6. When clients makes another request to backend with their session, backend picks an access token from the DB and can call an API.
like image 193
Michal Trojanowski Avatar answered Apr 29 '26 05:04

Michal Trojanowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!