2017-02-15 21 views
0

Я пытаюсь отключить или установить заголовок XFrameOptions в SAME_ORIGIN для определенного URL-адреса в моем проекте Spring Boot с Spring Security. Я вставив код ниже,Отключить заголовок ответа X-FrameOptions для URL 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. Например, следующий пример имеет другую конфигурацию для URL, которая соответствует **/course/embed/**. Если соответствия 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. Я получаю эту ошибку «Отказано в отображении« https: // localhost/modern/course/embed/33510 »в фрейме, потому что он устанавливает« X-Frame-Options »в« DENY », когда вызывается«/course/embed » , Таким образом, antMatcher все еще не соответствует шаблону. Я что-то упускаю? – arjary

+0

Если ваш URL-адрес/курс/встраивание, шаблон должен быть установлен как/course/embed * – mhshimul

+0

Извините, я пропустил ваш полный URL-адрес. попробуйте с этим/**/course/embed/** – mhshimul