Spring Security允​​许路径具有相同的后缀

时间:2018-10-02 04:44:23

标签: java spring spring-mvc spring-security

在我的JWT身份验证API中,我希望这些路径无需任何身份验证即可访问,并且禁止/禁用所有其他端点:

  • 获取/ apis / id / {id}
  • POST / apis
  • 匹配/ apis / id / {id}
  • 删除/ apis / id / {id}
  • 获取/swagger-ui.html

如您所见,以上大多数端点都以/apis/id开头,而POST具有/apis。这是我的配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests()
           .mvcMatchers(HttpMethod.GET,"/apis/id/**").permitAll()
           .mvcMatchers(HttpMethod.PATCH,"/apis/id/**").permitAll()
           .mvcMatchers(HttpMethod.DELETE,"/apis/id/**").permitAll()
           .mvcMatchers(HttpMethod.POST,"/apis", "/apis/").permitAll()
           .antMatchers(HttpMethod.GET,"/csrf","/v2/api-docs","/swagger-resources/configuration/ui",  "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**","/swagger-resources/configuration/ui","/swagger-resources/configuration/security", "/configuration/security").permitAll()// for Swagger UI
        .anyRequest().denyAll();
    }
}

只有GET /apis/id/{id}/swagger-ui.html通过。具有相同配置的其他端点(POST除外)都被拒绝(403)。我添加了一个异常处理程序并打印出AuthenticationException消息,内容为:

  

访问此资源路径需要完全认证

如何使这些端点公开?我感觉好像缺少一些配置。

我正在使用的Framworks:

  • Spring Boot版本2.0.4
  • Spring Security版本5.1.0

2 个答案:

答案 0 :(得分:2)

您可以查看this answer,以获取有关您的问题的可能解释。

  

调用antMatcher(String)将覆盖以前的调用   mvcMatcher(String)requestMatchers()antMatcher(String),   regexMatcher(String)requestMatcher(RequestMatcher)

现在您已经了解了潜在的问题,现在可以将代码更改为以下内容:

http
    .requestMatchers()
        .antMatchers("/apis/id/**", "/csrf","/v2/api-docs","/swagger-resources/configuration/ui",  "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**","/swagger-resources/configuration/ui","/swagger-resources/configuration/security", "/configuration/security").permitAll()
        .anyRequest().authenticated();

答案 1 :(得分:0)

使用以下内容进行不认证

  @Override
  public void configure(WebSecurity web) {
      // Overridden to exclude some url's 
      web.ignoring().antMatchers("/url_to_exclude");
  }

现在剩下的网址了

   @Override
   protected void configure(HttpSecurity http) throws Exception {
    // configure the other url's as required
   }