【问题标题】:Configuring public endpoints with Spring Boot / Spring Security works for GET but not for POST使用 Spring Boot / Spring Security 配置公共端点适用于 GET 但不适用于 POST
【发布时间】:2021-01-28 18:48:47
【问题描述】:

我的 Spring Boot 应用程序提供了几个端点。在this article 之后,我想默认限制所有端点,以便它们需要通过 JWT 令牌进行身份验证。只有某些路径是公开的。我的理解是.antMatchers(PUBLIC_RESOURCES).permitAll() 中定义的所有路径都将是“公共”的,无需任何身份验证。

这适用于 GET 方法,但是当使用 POST 访问相同的端点时,我得到一个 HTTP 403(禁止)。我不明白这是为什么。

这是我当前的安全配置:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final String[] PUBLIC_RESOURCES = {
            "/",
            "/user/login"
    };

    @Override
    protected void configure(final HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .antMatcher("/**").authorizeRequests()
                .antMatchers(PUBLIC_RESOURCES).permitAll()
                .anyRequest().authenticated();
    }
}

还有控制器:

@RestController
@RequestMapping(path = "user")
public class LoginController {

    @GetMapping
    public String get() {
        return "Hey, Joe (get)";
    }

    @PostMapping
    public String post() {
        return "Hey, Joe (post)";
    }
}

【问题讨论】:

    标签: spring-boot spring-security


    【解决方案1】:

    这可能是因为CSRF 保护会影响所有改变服务器状态的请求(POST、PUT、DELETE 等)。

    您可以在此处阅读有关 csrf 的更多信息:

    What is CSRF?

    How to configure or disable csrf in spring security.

    我猜你想禁用它(我不推荐,因为它是一项安全功能)

    如何在 Spring Security 中禁用 csrf。

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) {
            http
                .csrf(csrf -> csrf.disable());
        }
    }
    

    我强烈建议打开 Spring Security 调试日志记录,日志会告诉您请求被拒绝的确切原因。

    application.properties

    logging.level.org.springframework.security=DEBUG
    

    【讨论】:

    • 谢谢,这澄清了事情。禁用 CSRF 的快速测试表明这是根本原因。我最终将.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) 添加到安全配置中。
    猜你喜欢
    • 2018-02-03
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2019-03-08
    • 2018-12-07
    • 2021-08-25
    相关资源
    最近更新 更多