2017-02-15 90 views
0

我正试图在Spring Security项目的Spring Boot项目中为特定URL禁用或设置XFrameOptions标头为SAME_ORIGIN。我粘贴下面的代码,为URL禁用X-FrameOptions响应标题Spring Security JAVA配置

@Configuration 
@EnableWebSecurity  
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {  
    @Override 
    protected void configure(HttpSecurity http) throws Exception {    
     RequestMatcher matcher = new AntPathRequestMatcher("**/course/embed/**"); 

     DelegatingRequestMatcherHeaderWriter headerWriter = 
       new DelegatingRequestMatcherHeaderWriter(matcher,new XFrameOptionsHeaderWriter()); 

     http.headers() 
       .frameOptions().sameOrigin() 
       .addHeaderWriter(headerWriter); 
    }  
} 

我使用AntRequestMatcher但不起作用,它,而不是禁用XFrameOptions头所有响应。有一个更好的方法吗?请帮忙。

回答

0

您需要配置多个HttpSecurity实例。关键是多次扩展WebSecurityConfigurationAdapter。例如,以下是针对与**/course/embed/**匹配的URL的不同配置的示例。如果匹配X-Frame-Options将是SAMEORIGIN,否则是DENY。

@EnableWebSecurity 
public class WebMVCSecurity { 
    //Configure Authentication as normal, optional, showing just as a sample to indicate you can add other config like this 
    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth.inMemoryAuthentication() 
       .withUser("user").password("password").roles("USER").and() 
       .withUser("admin").password("password").roles("USER", "ADMIN"); 
    } 

    // Create an instance of WebSecurityConfigurerAdapter that contains @Order to specify which WebSecurityConfigurerAdapter should be considered first. 
    @Configuration 
    @Order(1) 
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { 
     protected void configure(HttpSecurity http) throws Exception { 
      // The http.antMatcher states that this HttpSecurity will only be applicable to URLs that match with **/course/embed/** 
      http.antMatcher("**/course/embed/**").headers().frameOptions().sameOrigin(); 
     } 
    } 

    // Create another instance of WebSecurityConfigurerAdapter. 
    // If the URL does not match with **/course/embed/** this configuration will be used. 
    // This configuration is considered after ApiWebSecurityConfigurationAdapter since it has an @Order value after 1 (no @Order defaults to last). 
    @Configuration 
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { 
     @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http.authorizeRequests() 
        .anyRequest().authenticated() 
        .and() 
        .formLogin(); 

      //bla bla bla ... 
     } 
    } 
} 
+0

谢谢,我试了多个WebSecurityConfigurerAdapter。当“/ course/embed”被调用时,我得到这个错误“拒绝在一个框架中显示'https:// localhost/modern/course/embed/33510',因为它将'X-Frame-Options'设置为'DENY'” 。所以antMatcher仍然不符合模式。我错过了什么吗? – arjary

+0

如果你的网址是/ course/embed,那么pattern应该设置为/ course/embed * – mhshimul

+0

对不起,我错过了你的完整url路径。尝试用这个/ ** /当然/嵌入/ ** – mhshimul