Spring启动csrf过滤器

3 java spring spring-mvc spring-security spring-boot

我试图为某些特定的api调用启用csrf过滤器,而其他人则不需要csrf过滤器.我所做的是

@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();
}
Run Code Online (Sandbox Code Playgroud)

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

出现错误

"message":"缺少或不匹配的CSRF令牌"

我正在使用Spring启动和Spring Security.

谢谢你的帮助.

Soh*_*ham 5

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

或者你可以这样做.我想两者都会奏效.

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