Securing Spring boot apps with Basic Auth and Keycloak

Hesham A. Othman
Aug 24, 2021 · 2 min read

In this tutorial, I am going to present how to integrate secure Spring Boot apps with Keycloak on top of Basic authentication. This integration might become handy in many situations.

This was the case for a task that I had some time ago, where we needed to secure the “Actuator” endpoints with basic auth for Kubernetes to be able to communicate with the pods to fetch metrics such as Health, Info.

At the same time, we wanted to secure other endpoints with keycloak for normal interaction with the service. This helps the loose coupling design of the services as the services will still function if the keycloak server was down for any reason.


The problem why this integration does not work smoothly as one might expect is that both security mechanisms overlap with each other. The filter intercepts every request with an HTTP Authorization header. so if the request does not have the header “Bearer: ****” it will be rejected and redirected to keycloak to be authenticated, even if the request is authenticated with any other mechanism, Basic-auth for example.


The solution idea here is to simply register the filter of Basic-Auth before the keycloak filter. This could be easily done using the @order annotation form spring. It will simply allow us to arrange the order of our configurations as we need.

We will start with the first configuration class, and that is the Basic-Auth filter:

In order to make this class as handy as possible, we added this “endPointMathcher” to be able to register as many endpoints as we want to be authenticated under Basic-Auth. It takes a comma-separated list from the configuration file, e.g. Yaml, and matches it.

Then we will register the Keycloak filter as shown below. This filter will authenticate any other endpoint with a specified client a role.

now we are finished with the java configuration. we still however need to create the keycloak needed configuration, e.g. create a client and assign a role to it and adapt the YAML/properties file with this information accordingly. This way we can deploy our service and still be able to change any of the configs without the need to redeploy it.

A complete working example of this tutorial can be found here.


Medium’s largest Java publication, followed by 14630+ programmers. Follow to join our community.