Spring 启动 csrf 过滤器

Spring boot csrf filter

我试图为某些特定的 api 调用启用 csrf 过滤器,而对于其他不需要 csrf 的调用 filter.What 我已经做到了

@Override

protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable().authorizeRequests().antMatchers("/public/**").permitAll();
    http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
    http.csrf().disable().addFilterBefore(new StatelessCSRFFilter(), CsrfFilter.class).authorizeRequests().antMatchers("/rest/**").permitAll();
}

问题是当我调用 localhost:8080/public/hello

显示错误

"message": "Missing or non-matching CSRF-token"

我正在使用 Spring 启动和 Spring 安全。

感谢您的帮助。

尝试将 http.csrf().disable() 更改为 http.antMatcher("/public/**").csrf().disable()http.antMatcher("/rest/**").csrf().disable()。您可能必须将这两行分别放在它们自己的 WebSecurityConfigurerAdapter 中。

这将告诉 Spring-Security 创建多个 HTTP 安全过滤器链(类似于在 XML 模型中有多个 <http/> 块)。

http.antMatcher("/public/**").authorizeRequests().anyRequest().permitAll();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
http.antMatcher("/rest/**").addFilterBefore(new StatelessCSRFFilter(), CsrfFilter.class).csrf().disable();

或者你可以这样做 this.I 认为两者都会起作用。

http.antMatcher("/public/**").csrf().disable();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
http.antMatcher("/rest/**").addFilterBefore(new StatelessCSRFFilter(), CsrfFilter.class).csrf().disable();