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!