How to add headers to requests ignored by Spring Security

狂风中的少年 提交于 2021-02-18 18:48:54

问题


My configuration of Spring Security is

@Override
  public void configure(WebSecurity web) throws Exception {
    web
      .ignoring()
         .antMatchers("/resources/**"); // #3
  }

Taken from here. The documentation for ignorig says

Allows adding RequestMatcher instances that should that Spring Security should ignore. ... Typically the requests that are registered should be that of only static resources.

I would like to add some headers to files served from resources. E.g.: Strict-Transport-Security: max-age=31536000, X-Content-Type-Options: nosniff.

How I can do it?


回答1:


One solution it to change it to

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/resources/**").permitAll()
       .and()
       .antMatcher("/resources/**").headers().cacheControl()
}

Example how to allow cache control headers PLUS ALL DEFAULT SPRING SECURITY HEADERS.




回答2:


I have struggled with the same problem. When I ignore specific requests in WebSecurity, the headers were gone.

I fixed the missing headers, by applying a filter on each request that adds my headers.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .addFilterBefore(securityHeaderFilter, BasicAuthenticationFilter.class)
        ...
}

The filter code looks like this. The important thing to note here, is that the Filter must be declared as a @Component. When you miss the @Component annotation, the filter will be ignored.

@Component
public class SecurityHeaderFilter implements Filter {

    @Override
    public void init(FilterConfig fc) throws ServletException {
        // Do nothing
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader(
                "custom-header1", "header-value1");
        httpServletResponse.setHeader(
                "custom-header2", "header-value2");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // Do nothing
    }
}


来源:https://stackoverflow.com/questions/44672913/how-to-add-headers-to-requests-ignored-by-spring-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!