gpt4 book ai didi

java - 禁用 URL Spring Security JAVA 配置的 X-FrameOptions 响应 header

转载 作者:行者123 更新时间:2023-11-29 04:34:32 24 4
gpt4 key购买 nike

我正在尝试使用 Spring Security 为我的 Spring Boot 项目中的特定 URL 禁用 XFrameOptions header 或将其设置为 SAME_ORIGIN。我粘贴下面的代码,

@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 header 。有一个更好的方法吗?请帮忙。

最佳答案

您需要配置多个 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 ...
}
}
}

关于java - 禁用 URL Spring Security JAVA 配置的 X-FrameOptions 响应 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42257402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com