Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Keycloak authentication - serves both web application and web service

Our stack includes the following services, each service runs in a docker container:

  • Front-end in React
  • Backend service based on Spring boot "resource-service"
  • Keycloak
  • Other backend service (consumer)

Both the front-end and the consumer services communicate with the backend using REST API. We use Keycloak as our user management and authentication service.

We would like to integrate our Spring based service "resource-service" with Keycloak by serving both web application and a service flows:

  1. Web application - React based front-send that should get a redirect 302 from the "resource-service" and send the user / browser to login in the Keycloak site and then return to get the requested resource.

  2. Server 2 Server coomunication - A server that need to use the "resource-service" API's should get 401 in case of authentication issues and not a redirection / login page.

There are few options to integrate Spring with Keycloak:

  1. Keycloak Spring Boot Adapter
  2. Keycloak Spring Security Adapter
  3. Spring Security and OAuth2

I noticed that there is a "autodetect-bearer-only" in Keycloak documentation, that seems to support exactly that case. But - There are a lot of integration options and I'm not sure what is the best way to go, for a new Spring boot service. In addition, I didn't find where to configure that property.

like image 519
kmualem Avatar asked Jan 24 '26 09:01

kmualem


1 Answers

I've used approaches one and two and in my opinion, if you are using Spring Boot, use the corresponding adapter, use the Spring Security adapter if you're still using plain Spring MVC. I've never seen the necessity for the third approach as you basically have to do everything on your own, why would anyone not use the first two methods?

As for using the Spring Bood adapter, the only configuration necessary is the following:

keycloak:
  bearer-only: true
  auth-server-url: your-url
  realm: your-realm
  resource: your-resource

And you're done. The bearer-only is so that you return 401 if a client arrives without a bearer token and isn't redirected to a login page, as you wanted. At least that's what's working for us :-)

After that, you can either use the configuration for securing endpoints but it's a bit more flexible to either use httpSecurity or @EnableGlobalMethodSecurity which we're doing with e. g. @Secured({"ROLE_whatever_role"}).

If you're using the newest Spring Boot version combined with Spring Cloud, you might run into this issue.

like image 75
N4zroth Avatar answered Jan 26 '26 02:01

N4zroth



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!