I am trying to use Spring's Oauth2RestTemplate, but we need it to use some super user when making a Rest call (we have the user defined), rather than it passing through the user that originally made the service call.
So here's the situation:
userA
makes a call to endpointA
. Naturally, he has permission to hit this endpoint (based on permitted actions in his assigned roles in Keycloak). endpointA
will then make a Rest call using the OAuth2RestTemplate to another service, endpointB
. However, userA
does not have permission to hit that endpoint. This call should be made as a service-user
, who in our keycloak, is essentially a super user that can do anything. The problem is, the OAuth2RestTemplate is keeping the same user that made the original call (userA
) - since he is not permitted to access that endpoint, the call fails (based on RBAC stuff we have set up, separate from the Oauth2 security side of things).
Is there a way to hit an endpoint using userA
, who has limited access, and have it trigger making a REST call through the OAuth2RestTemplate using a service-user
that has access to everything? Note: the OAuth2 info for that service-user
should still be retrieved the same as it would be as if it were still userA
(lookup in keycloak). Essentially, this would just be us changing the username before making the REST call (well... I think that's what it entails).
Note: I found a way to temporarily get passed this. That is by creating a new thread before making the REST call. This works because Spring no longer has access to the user's security context in that new thread, forcing it to retrieve a new token using the security details provided when creating the OAuth2RestTemplate. This shows that another solution (and actually preferred) would be to force the OAuth2RestTemplate to always retrieve a new token when hit (using the ResourceDetails, not a "refresh" of the user's token), rather than using the one stored in the SecurityContextHolder at the start of the request.