【问题标题】:Failing to exclude one URI from Spring Security protection on a POST request未能在 POST 请求中从 Spring Security 保护中排除一个 URI
【发布时间】:2016-07-15 02:05:43
【问题描述】:

我有一个HttpSecurity,如下所示:

http
   .exceptionHandling().and()
   .anonymous().and()
   .servletApi().and()
   .headers().cacheControl().and().and()
   .authorizeRequests()
       // Need authentication sur POST
       .antMatchers(HttpMethod.POST).authenticated()
       // Allow anonymous resource requests
       .anyRequest().permitAll().and()
   // Custom Token based authentication based on the header previously given to the client
   .addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService),
                        UsernamePasswordAuthenticationFilter.class)
   // Filtre pour gérer la clef d'api
   .addFilterBefore(new ApiKeyFilter(), StatelessAuthenticationFilter.class)
   // Filtre pour ajouter les headers nécessaires à la consommation par les différents clients
   .addFilterBefore(new CorsFilter(), ApiKeyFilter.class);

问题是我需要能够在/userPOST 而不会得到403 Forbidden 的响应。所以我想添加一个规则来允许/userPOST 上的匿名请求。

我用过这个antMatcher

.antMatchers(HttpMethod.POST, "/user").anonymous()

但问题是我不知道在哪里添加这个,我在.antMatchers(HttpMethod.POST, "/user").anonymous() 之前和之后尝试过,但似乎它被忽略了,因为我仍然得到一个403

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    antMatchers(HttpMethod.POST).authenticated() 之前添加规则。此外,由于默认启用CSRF 保护,您应该禁用它或在您的POST 请求中提供 CSRF 令牌。这里我只是禁用 CSRF:

    // Same as before
    .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/user").permitAll()
        // Need authentication sur POST
        .antMatchers(HttpMethod.POST).authenticated()
        // Allow anonymous resource requests
        .anyRequest().permitAll()
    .and
    .csrf().disable();
    // Same as before
    

    您可以在 Spring Security Documentation 上阅读有关 CSRF 的更多信息。

    【讨论】:

      猜你喜欢
      • 2016-07-17
      • 2018-08-02
      • 2013-06-25
      • 2016-01-08
      • 2023-01-11
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多