How to Set Up Backend Authentication Using Spring Boot and Keycloak

I’m working on a microservices application and need to implement secure authentication between my backend services while using Keycloak and Spring Boot, specifically with Spring Security and JWT tokens in bearer-only mode.

One of my backend services needs authentication to provide access to its REST endpoints. This service supplies data for a web UI and stores data in a database for later processing. User authentication in the UI is functioning correctly.

In addition, I have another background service that performs calculations and needs to access the previously mentioned service, which requires an access token from Keycloak for valid HTTP POST requests.

I am attempting to use KeycloakRestTemplate to execute the post requests, but I encounter an exception when calling the .postForObject method:

Caused by: java.lang.IllegalStateException: Cannot set authorization header because there is no authenticated principal

This suggests that the calculations service is not retrieving the authentication token before making requests to the other REST service. Despite extensive research into Keycloak specifics, I haven’t identified the solution yet. Could anyone provide guidance?

Here’s the configuration for my calculation service in the application.properties file:

keycloak.auth-server-url=http://localhost/auth
keycloak.realm=myrealm
keycloak.bearer-only=true
keycloak.resource=backend-service2
keycloak.principal-attribute=preferred_username
keycloak.cors=true
keycloak.realm-key=<PUBKEY>
keycloak.credentials.secret=<SECRET_UUID_STYLE>
keycloak.use-resource-role-mappings=true

Also, I have three clients set up within Keycloak: webui, backend-service1, and backend-service2, both backend services marked as bearer-only.

I’m still receiving exceptions, and I suspect there may be issues with the configuration, specifically with token access. Any insights would be very helpful!

I’ve encountered a similar issue before. The exception you’re experiencing often indicates that the bearer-only mode prevents your background service from authenticating on its own, as it cannot issue tokens. Instead, try setting up the calculation service with confidential client mode in Keycloak rather than bearer-only. This way, the service can obtain a token using client credentials, either through a setup with RestTemplate or WebClient, and then include that token in REST requests to authenticate successfully. Ensure the new client secret you’ve configured in Keycloak is correctly set up in your application.properties file.

you might also iwant to check if the Keycloak config is actually visible and correctly loaded by the microservice container. Sometimes env variables override what’s in application.properties file if things are set up in both places.