I'm having 2 services: service A (spring boot and openfeign for http client) and service B. My services are behind a gateway (APISIX), which is integrated with keycloak. Both services are configured OAuth2 to expose to public.
There is a use case, when a logged in user requests to service A, and service A requests to service B using openfeign. What is the proper way to pass OAuth2 credential to OpenFeign client when requesting to service B?
Thank you very much.
CodePudding user response:
In the case you're on a resource-server and want to issue a request from that resource-server on behalf of the authenticated user, you should be able to
access the Bearer token from the Authentication instance in the security-context.
Default Authentication types are JwtAuthenticationToken for resource-servers with JWT decoder and BearerTokenAuthentication for those with introspection.
You can query directly the SecurityContext of the request:
final AbstractOAuth2TokenAuthenticationToken<? extends AbstractOAuth2Token> auth = (AbstractOAuth2TokenAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
final String bearerToken = auth.getToken().getTokenValue();
or have it auto-magically injected as @Controller method parameter:
@RestController
public class MyController {
@GetMapping("/reflect-bearer-token")
@PreAuthorize("isAuthenticated()")
public String reflectBearerToken(AbstractOAuth2TokenAuthenticationToken<? extends AbstractOAuth2Token> auth) {
return auth.getToken().getTokenValue();
}
First option (querying security-context) can be applied in a a feign RequestInterceptor to add an Authorization header with authenticated user Bearer to every request.
