Having 2 microservices, one rest service one is websocket service. Websocket service has feign client to talk to the rest service.
When calling rest service from a browser tool (postman eg) the call works correctly. We pass only the header Authorization
with value Bearer XXXXX
When calling from feign without interceptor we get a 401: unauthorized, which is correct behaviour.
When adding this interceptor to the codebase, were as XXXXX is the real token of course, we receive a 403
@Component
public class FeignOauth2Interceptor implements RequestInterceptor {
private static final String AUTHORIZATION_HEADER = "Authorization";
@Override
public void apply(RequestTemplate template) {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication =
securityContext.getAuthentication();
template.header(AUTHORIZATION_HEADER, "Bearer XXXXX");
}
}
The interceptor is called as we see a different error code after adding it, we went from 401 to 403.
What are we missing here ??
Thanks in advance
I think it's not a good idea the hardcoding of your token in the interceptor, you can get a token from the OAuth2AuthenticationDetails:
@Bean
public RequestInterceptor requestTokenBearerInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication == null) return;
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
requestTemplate.header("Authorization", "Bearer " + details.getTokenValue());
}
};
}
Also, you can use the OAuth2FeignRequestInterceptor, which get your token from a context and refresh it itself when it's needed. In my opinion, this is a better solution. You can find an example of using it here: https://stackoverflow.com/a/53454703/10697598