Spring boot 在与API密钥身份验证集成后,无法将permitAll()与Spring Boot 2.3.4一起使用,以允许访问Swagger UI

Spring boot 在与API密钥身份验证集成后,无法将permitAll()与Spring Boot 2.3.4一起使用,以允许访问Swagger UI,spring-boot,spring-security,swagger,spring-security-rest,Spring Boot,Spring Security,Swagger,Spring Security Rest,我尝试通过以下方式将API密钥身份验证机制集成到Spring Boot应用程序中: 创建了一个CustomAPIKeyAuthFilter,它扩展了AbstractPreAuthenticatedProcessingFilter,从请求的头中获取预验证主体 公共类CustomAPIKeyAuthFilter扩展了AbstractPreAuthenticatedProcessingFilter{ 私有字符串principalRequestHeader; 私有字符串principalAuthKey;

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

  • 创建了一个
    CustomAPIKeyAuthFilter
    ,它扩展了
    AbstractPreAuthenticatedProcessingFilter
    ,从请求的头中获取预验证主体
  • 公共类CustomAPIKeyAuthFilter扩展了AbstractPreAuthenticatedProcessingFilter{
    私有字符串principalRequestHeader;
    私有字符串principalAuthKey;
    公共CustomApikeAuthFilter(String principalRequestHeader、String principalAuthKey){
    this.principalRequestHeader=principalRequestHeader;
    this.principalAuthKey=principalAuthKey;
    }
    @凌驾
    受保护对象getPreAuthenticatedPrincipal(HttpServletRequest){
    返回请求.getHeader(principalRequestHeader);
    }
    @凌驾
    受保护对象getPreAuthenticatedCredentials(HttpServletRequest){
    //这里有什么要退的吗??
    返回“待定”;
    }
    }
    
  • 创建了扩展
    WebSecurityConfig适配器的
    WebSecurityConfig
    。在本例中,自定义筛选器被注入到重写的方法
    protectedvoidconfigure(HttpSecurity-HttpSecurity){}
  • @EnableWebSecurity
    @订单(1)
    公共类WebSecurityConfig扩展了WebSecurityConfigureAdapter{
    @值(“${superuser}”)
    私有字符串principalRequestHeader;
    @值(“${superuserauthkey}”)
    私有字符串principalRequestValue;
    @凌驾
    受保护的无效配置(HttpSecurity HttpSecurity)引发异常{
    CustomAPIKeyAuthFilter=new CustomAPIKeyAuthFilter(principalRequestHeader,principalRequestValue);
    filter.setAuthenticationManager(新的AuthenticationManager(){
    @凌驾
    公共身份验证(身份验证)引发AuthenticationException{
    字符串主体=(字符串)身份验证。getPrincipal();
    if(principalRequestValue.equals(principal)){
    authentication.setAuthenticated(true);
    }否则{
    抛出新的BadCredentialsException(“缺少API密钥”);
    }
    返回认证;
    }
    });
    httpSecurity。
    cors()和()。
    csrf().disable().authorizeRequests()
    .antMatchers(“**swagger**”).permitAll()//这是对我不起作用的部分
    .anyRequest().authenticated()
    .及()
    .addFilter(过滤器)
    .sessionManagement().sessionCreationPolicy(sessionCreationPolicy.STATELESS);
    }
    }
    
    从上面的评论中可以看出,即使我使用了
    permitAll
    ,如果我尝试访问在pom.xml中引入spring boot starter安全相关依赖项之前工作的Swagger UI,在运行时在请求中未找到预验证主体,我也会得到错误401
    。是否有更好的方法将swagger UI从需要基于API密钥的身份验证的URL端点列表中排除


    注意:我使用的是springfox-Swagger 2对Swagger的实现,使用的版本是2.8.0。

    Swagger有api端点,这应该是安全级别允许的,请在
    WebSecurityConfig.class

    @覆盖
    public void configure(WebSecurity web)引发异常{
    忽略()antMatchers(“/v2/api文档”,
    “/configuration/ui”,
    “/swagger resources/**”,
    “/configuration/security”,
    “/swagger ui.html”,
    “/webjars/**”);
    }
    
    您也可以尝试
    permitAll()
    对包含的模式进行验证。这将从身份验证中排除招摇过市者