0

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.

Sean
  • 139
  • 1
  • 1
  • 15

1 Answers1

0

I ended up just clearing the context before making the REST call:

SecurityContextHolder.clearContext()

When the OAuth2RestTemplate goes to make the call, it will check to see if Authentication has been done through that holder. If it does not see a token (which is the case when you clear the context), it will look up a new token using the OAuth2 configuration defined in the ResourceDetails. Just make sure that it references a client that has the permissions required.

Sean
  • 139
  • 1
  • 1
  • 15