我正在尝试使用此配置将 Spring 安全性禁用到最新的 Spring Cloud:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
@Order(SecurityProperties.DEFAULT_FILTER_ORDER)
public class WebSecurityConfigSec extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().cors().disable()
.authorizeRequests().anyRequest().permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/**");
}
}
应用程序.yml
spring:
main:
allow-bean-definition-overriding: true
security:
ignored=/**:
enable-csrf: false
我也尝试补充:
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable();
}
}
但它不起作用。
我得到错误:
An expected CSRF token cannot be found
18:16:24.537 [boundedElastic-2] DEBUG DefaultWebSessionManager[lambda$createWebSession$3:94] - Created new WebSession.
18:16:24.540 [boundedElastic-2] DEBUG HttpWebHandlerAdapter[traceDebug:91] - [1ffd0a30] Completed 403 FORBIDDEN
你知道我怎么解决这个问题吗?
从 pom.xml 中排除 MVC 依赖
并添加:
spring:
main:
web-application-type: reactive
这对我有用;由于启用了 Spring MVC 中使用的 spring security,我收到了 CSRF 错误。
@Bean
SecurityWebFilterChain springSecurityFilterChain(
ServerHttpSecurity http,
ReactiveClientRegistrationRepository clientRegistrationRepository
){
return http
...
.csrf(csrf -> csrf.csrfTokenRepository(
CookieServerCsrfTokenRepository.withHttpOnlyFalse()))
.build();
}
@Bean
WebFilter csrfWebFilter() {
//A filter with the only purpose of subscribing to the CsrfToken reactive stream and ensuring its value is extracted correctly
return (exchange, chain) -> {
exchange.getResponse().beforeCommit(() -> Mono.defer(() -> {
Mono<CsrfToken> csrfToken =
exchange.getAttribute(CsrfToken.class.getName());
return csrfToken != null ? csrfToken.then() : Mono.empty();
}));
return chain.filter(exchange);
};
}