spring-bootspring-cloud-gatewaystrict-transport-security

Enable HSTS support for static pages in spring cloud gateway


I am using the spring cloud gateway to run my angular application. The API gateway also acts as an entry point to the underlying microservices.

I have one microservice which is built on spring-web and one interceptor enables HSTS in the response headers.

My angular application has some static files. When these files are requested, the response headers do not have HSTS enabled. Any network calls to the micro-services do have the HSTS in the response headers.

enter image description here

This is a call to a micro-service and the response headers have HSTS

enter image description here

Is there anything to be configured in the spring cloud gateway for static pages? Please help


Solution

  • I added the below filter and it works.

    @Component
    public class HstsFilter implements WebFilter {
    
    private static final String PATH ="cms-service/webapi";
    private static final Logger LOGGER = LoggerFactory.getLogger(HstsFilter.class);
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        LOGGER.debug("Received request for URL: {}", exchange.getRequest().getURI());
            ServerHttpResponse response = exchange.getResponse();
            LOGGER.debug("Before modification, response headers: {}", response.getHeaders());
            if (!exchange.getRequest().getURI().getPath().contains(PATH) && !exchange.getRequest().getURI().getPath().contains("grafana")) {
                response.getHeaders().add("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
                response.getHeaders().add("Cache-Control", "no-store"); // HTTP 1.1.
                response.getHeaders().add("Pragma", "no-cache"); // HTTP 1.0.
                response.getHeaders().add("Expires", "0"); // Proxies.
                response.getHeaders().add("X-Frame-Options", "DENY");
            }
            LOGGER.debug("After modification, response headers: {}", response.getHeaders());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            LOGGER.debug("Response headers after processing: {}", exchange.getResponse().getHeaders());
            LOGGER.debug("Response status code after processing: {}", exchange.getResponse().getStatusCode());
        }));
    }