I’m trying to follow this example to pass the access token from an Angular client to proxied routes from the zuul api gateway. However, in my AuthorizationHeaderFilter class:
@component
public class AuthorizationHeaderFilter extends ZuulFilter {
private final OAuth2AuthorizedClientService authClientService;
public AuthorizationHeaderFilter(OAuth2AuthorizedClientService authClientService) {
this.authClientService = authClientService;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
RequestContext requestContext = RequestContext.getCurrentContext();
Optional<String> authorizationHeader = getAuthorizationHeader();
authorizationHeader.ifPresent(s -> requestContext.addZuulRequestHeader("Authorization", s));
return null;
}
private Optional<String> getAuthorizationHeader() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
OAuth2AuthenticationToken authToken = (OAuth2AuthenticationToken) authentication;
OAuth2AuthorizedClient authClient = authClientService.loadAuthorizedClient(
authToken.getAuthorizedClientRegistrationId(),
authToken.getName());
OAuth2AccessToken authAccessToken = authClient.getAccessToken();
if(authAccessToken == null) {
return Optional.empty();
} else {
String tokenType = authAccessToken.getTokenType().getValue();
String authorizationHeaderValue = String.format("%s %s", tokenType, authAccessToken.getTokenValue());
return Optional.of(authorizationHeaderValue);
}
}
@Override
public String filterType() {
return PRE_TYPE;
}
@Override
public int filterOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
the SecurityContextHolder seems to be returning a JwtAuthenticationToken object instead of the expected OAuth2AuthenticationToken object as I’m getting the following exception:
Caused by: java.lang.ClassCastException:
org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken
cannot be cast to
org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken
How can I use the JwtAuthenticationToken along with the OAuth2AuthorizedClientService to get the access token?