【问题标题】:Spring security antMatchers not being applied on POST requests and only works with GETSpring security antMatchers 未应用于 POST 请求,仅适用于 GET
【发布时间】:2018-12-07 08:09:44
【问题描述】:

我正在使用 Spring 安全库来保护我的应用程序中的 REST api,我现在正在尝试允许访问所有 URL(暂时)但是通过以下配置我发现只允许 GET 请求但不允许 POST 请求(其中我得到 403 禁止响应),我知道下面的第一个 antmatcher 应该同时允许 GET 和 POST,但实际上 2 个 antMatcher 不允许 POST

有人可以告诉我我在这里缺少什么吗?

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
// first I have tried only this antMatcher
            .antMatchers("/**").permitAll()
// But then it didn't allow POST even when only using the line below
            .antMatchers(HttpMethod.POST, "/**").permitAll()
}

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    经过一番调查,事实证明 antMatcher 正在按预期工作并允许所有 URL 按预期进行,但我收到的 POST API 被禁止响应的原因是 Spring 安全性正在等待这些 POST 的 csrf 令牌请求,因为在 Spring Security 中默认启用 CSRF 保护。

    所以为了让它像这样工作,你必须在 POST 请求中提供 csrf 令牌,或者你可以暂时关闭 CSRF 保护(但你应该在投入生产之前再次启用它,因为这是一个严重的攻击)

    示例代码:

    protected void configure(HttpSecurity http) throws Exception {
        http
            // disabling csrf here, you should enable it before using in production
            .csrf().disable()
            .authorizeRequests()
           // this matcher is working for all GET/POST/... , any URL matching the reg expression
                .antMatchers("/**").permitAll()
    }
    

    【讨论】:

    • 同意csrf().disable(),没有任何POST,PUT和DELETE失败
    • 谢谢,我遇到了完全相同的问题,这让我发疯了
    • 很高兴帮助:)
    【解决方案2】:

    正如提问者在您自己的回复中所说,403 禁止错误可能是由 CSRF 保护引起的。但除了禁用此保护之外,您还可以像这样将一些 AntMatchers 排除在外:

    http
                    (...) // oculted for brevity
                    .and()
                    .csrf()
                        .ignoringAntMatchers("/api/a", "/api/b")
    

    【讨论】:

      【解决方案3】:

      你需要做类似的事情,你应该提到角色

      http
        .httpBasic().and()
        .authorizeRequests()
          .antMatchers(HttpMethod.POST, "/employees").hasRole("ADMIN")
          .antMatchers(HttpMethod.PUT, "/employees/**").hasRole("ADMIN")
      

      希望它能解决您的问题。

      【讨论】:

      • 谢谢,但我目前正在尝试 permitAll,因此不需要角色,这适用于 GET 但不适用于 POST
      • 试试这样 .antMatchers(HttpMethod.OPTIONS, tokenEndpointPath).permitAll()
      • 请添加此项,因为默认情况下 csrf 将启用 '.csrf().disable()'
      • 为什么要删除csrf保护?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 2018-04-22
      • 1970-01-01
      • 2019-09-15
      • 2022-01-23
      相关资源
      最近更新 更多