1

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

  • 获取 /apis/id/{id}
  • 发布 /api
  • 补丁 /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消息,它说:

访问此资源路径需要完全身份验证

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

我正在使用的框架:

  • Spring Boot 2.0.4 版
  • Spring Security 5.1.0 版
4

1 回答 1

2

您可以查看此答案以了解对您的问题的可能解释。

调用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();
于 2018-10-02T05:49:26.910 回答