If I got your question correctly you are trying to call a bearer-only service through another application that's already logged in, you also didn't mention if you are using Spring Boot or another framework like it, so I'll suppose that you are using the Spring Boot for your server-side application.
The following example reflects into a simple call of an authenticated API to another one, both using Spring Boot:
import org.keycloak.KeycloakPrincipal;
import org.keycloak.adapters.RefreshableKeycloakSecurityContext;
import org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
@Component
public class AnotherServiceClient {
public TypeOfObjectReturnedByAnotherService getFromAnotherService() {
RestTemplate restTemplate = new RestTemplate();
String endpoint = "http://localhost:40030/another/service/url";
String bearerToken = getAuthorizationToken();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "bearer " + bearerToken);
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<TypeOfObjectReturnedByAnotherService> response = restTemplate.exchange(endpoint, HttpMethod.GET, entity, TypeOfObjectReturnedByAnotherService.class);
return response.getBody();
}
private String getAuthorizationToken() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
SimpleKeycloakAccount details = (SimpleKeycloakAccount) authentication.getDetails();
KeycloakPrincipal<?> keycloakPrincipal = (KeycloakPrincipal<?>) details.getPrincipal();
RefreshableKeycloakSecurityContext context = (RefreshableKeycloakSecurityContext) getPrincipal().getKeycloakSecurityContext();
return context.getTokenString();
}
}
By that way is possible to send the actual valid token generated by your origin service to another service.