与API密钥身份验证集成后,无法在Spring Boot 2.3.4中使用allowAll来允许访问Swagger UI

问题描述

我尝试通过以下方式将API密钥身份验证机制集成到Spring Boot Application:

  1. 创建了一个扩展CustomAPIKeyAuthFilter的{​​{1}},该扩展会从请求的标头中获取经过预先认证的主体。
AbstractPreAuthenticatedProcessingFilter
  1. 创建了public class CustomAPIKeyAuthFilter extends AbstractPreAuthenticatedProcessingFilter { private String principalRequestHeader; private String principalAuthKey; public CustomAPIKeyAuthFilter(String principalRequestHeader,String principalAuthKey) { this.principalRequestHeader = principalRequestHeader; this.principalAuthKey = principalAuthKey; } @Override protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { return request.getHeader(principalRequestHeader); } @Override protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { // anything to be returned here?? return "TBD"; } } ,扩展了WebSecurityConfig。在此示例中,自定义过滤器被注入到覆盖的方法WebSecurityConfigurerAdapter
protected void configure(HttpSecurity httpSecurity) {}

从上面的注释中可以看到,即使我使用了@EnableWebSecurity @Order(1) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${superuser}") private String principalRequestHeader; @Value("${superuserauthkey}") private String principalRequestValue; @Override protected void configure(HttpSecurity httpSecurity) throws Exception { CustomAPIKeyAuthFilter filter = new CustomAPIKeyAuthFilter(principalRequestHeader,principalRequestValue); filter.setAuthenticationManager(new AuthenticationManager() { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String principal = (String) authentication.getPrincipal(); if (principalRequestValue.equals(principal)){ authentication.setAuthenticated(true); } else { throw new BadCredentialsException("Missing API Key"); } return authentication; } }); httpSecurity. cors().and(). csrf().disable().authorizeRequests() .antMatchers("**swagger**").permitAll() // this is the part that is not working for me .anyRequest().authenticated() .and() .addFilter(filter) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } } ,因为在运行时,如果我尝试访问在引入spring-boot之前已经起作用的Swagger UI,也会收到错误401 permitAll。 pom.xml中与-starter-security相关的依赖项。是否有更好的方法将单独的swagger UI排除在需要基于API密钥的身份验证的URL端点列表之外?

注意:我正在使用Swagger的springfox-swagger2实现,使用的版本是2.8.0。

解决方法

Swagger具有应在安全级别上允许的api端点,请在WebSecurityConfig.class中添加以下代码段

@Override
public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs","/configuration/ui","/swagger-resources/**","/configuration/security","/swagger-ui.html","/webjars/**");
}

您也可以尝试permitAll()尝试使用其中包含的模式。这样可以避免招摇过头的身份得到验证。