Reputation: 31
I want to remove the authorization-header in spring-cloud-gateway. Its not possible to do this by spring docs, because the header is readonly. The following code throws an UnexpectedOperationException
filters:
- AddRequestHeader=X-Custom-Header,CustomValue
- RemoveRequestHeader=Sensitive-Header
This is a part of my configuration in application.yml.
spring:
cloud:
gateway:
routes:
- id: test-route
uri: http://52.20.148.183
predicates:
- Path=/test/**
filters:
- StripPrefix=1
With every try, removing the header in code for example with GlobalFilter and exchange.mutate()..., I ran into error.
Only this way by chat-gpt works:
public class CustomRequestDecorator extends ServerHttpRequestDecorator {
public CustomRequestDecorator(ServerHttpRequest delegate) {
super(delegate);
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.putAll(super.getHeaders());
headers.remove(HttpHeaders.AUTHORIZATION);
headers.remove("Postman-Token");
return headers;
}
}
@Component
public class RemoveAuthenticationHeaderFilter implements GlobalFilter {
private Logger logger = LoggerFactory.getLogger(RemoveAuthenticationHeaderFilter.class);
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
logger.info("Removing authentication header");
var customRequest = new CustomRequestDecorator(exchange.getRequest());
var newExchange = exchange.mutate().request(customRequest).build();
return chain.filter(newExchange);
}
}
Did I make a misstake? This is not a good solution for future, because it is not possible, using default filters to mutate request-headers.
Upvotes: 1
Views: 125
Reputation: 12564
In your filter, instead of trying to alter the request, create a copy of it with modified headers.
Upvotes: 0