BrianRT
BrianRT

Reputation: 1972

Spring HttpSecurity overwrite response header

You can add a header to a response by doing

@EnableWebSecurity
public class CacheControl extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .headers()
      .addHeaderWriter(new StaticHeadersWriter("Cache-Control", "private, max-age=43200"));
  }
}

If the response already has a Cache-Control property, this just adds a second one to it with the same name:

Cache-Control: original content
Cache-Control: added content

Is there an easy way to overwrite the existing property?

Upvotes: 1

Views: 2837

Answers (1)

BrianRT
BrianRT

Reputation: 1972

The simplest solution I found was to disable Cache-Control, and then to add the Cache-Control header again.

@Configuration
@EnableWebSecurity
public class CacheControlAdapter extends WebSecurityConfigurerAdapter {
  public CacheControlAdapter() {}

  @Override
  @RequestMapping("/app/")
  protected void configure(HttpSecurity http) throws Exception {
    StaticHeadersWriter writer = new StaticHeadersWriter("Cache-Control", "value");
    http
      .headers()
      .cacheControl()
      .disable()
      .addHeaderWriter(writer);
  }
}

Upvotes: 1

Related Questions