如何让Spring Security允​​许匿名POST请求?

Mic*_*elK 4 java spring-security spring-boot

我有一个 Spring Boot Web 应用程序,其中大多数端点都需要身份验证。然而,少数映射应允许匿名访问;它们是一般规则的例外。

我无法让它适用于 POST 调用,他们总是收到 403。

安全配置...

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests().regexMatchers("/", "/posthello").anonymous()
        .and()
            .authorizeRequests().anyRequest().authenticated();
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器...

@RestController
public class HelloController {

    // This returns HTTP 200 and body on anonymous calls
    @GetMapping("/") 
    public String helloWorld() {
        return "Hello World!";
    }
    
    // This demands authentication, as expected
    @GetMapping("/gethello") 
    public String getHelloWorld(String body) {
        return "You got: Hello, World!";
    }
    
    // This always returns HTTP 403 on anonymous calls, 
    // even though it is supposed to be excepted
    @PostMapping("/posthello") 
    public String postHelloWorld(@RequestBody String body) {
        return "You posted: " + body;
    }   
}
Run Code Online (Sandbox Code Playgroud)

jzh*_*aux 5

Patel Romil 是正确的,403 是由 CSRF 引起的,禁用 CSRF 将禁用该保护。他还明智地警告不要在生产应用程序中这样做。

为整个站点禁用 CSRF 的另一种方法是指定端点允许列表,如下所示:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .ignoringAntMatchers("/posthello")
                .and()
            .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/posthello").anonymous()
                .anyRequest().authenticated();
    }
}
Run Code Online (Sandbox Code Playgroud)

也就是说,真正的解决方案可能是将应用程序配置为使用 CSRF 令牌。如果没有 CSRF 保护,任意第三方 Web 应用程序都可以调用POST /posthello.