OpenAPI3 通过 Spring Boot 显示基于基本身份验证的方法

tri*_*ogy 5 java spring spring-boot openapi springdoc-openapi-ui

我将此依赖项添加到我的 Spring Boot 应用程序中

 <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-ui</artifactId>
      <version>1.4.3</version>
      <type>pom.sha512</type>
     </dependency>
Run Code Online (Sandbox Code Playgroud)

然后我就可以打开:https://localhost:8443/v3/api-docs

浏览器确实会询问我的凭据,只要我正确输入用户/密码,它就可以工作,但它会向我显示全局可用的所有方法。我只希望用户有权使用的方法显示在 api 文档中。

对于特定方法是使用此标签来授权我的调用: @PreAuthorize("hasRole('USER') OR hasRole('ADMIN')")

这是我的网络安全配置类:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user").password(new BCryptPasswordEncoder().encode("blabl")).roles("USER")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("blabla")).roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }
}
Run Code Online (Sandbox Code Playgroud)

Dis*_*ble 1

根据您提供的描述,我会推荐以下内容。

  1. 在端点上添加角色特定的安全性:

例如:

@Override
protected void configure(HttpSecurity http) throws Exception {
http
      .authorizeRequests()
        .antMatchers("/rest/admin/**").hasAnyRole("ADMIN").and()
      .httpBasic()
        .and()
    .csrf().disable();   
}
Run Code Online (Sandbox Code Playgroud)
  1. 将“ ROLE_”添加到您的@PreAuthorize

例如:

@PreAuthorize("hasRole('ROLE_USER')")
Run Code Online (Sandbox Code Playgroud)

或者

@PreAuthorize("hasRole('ROLE_ADMIN')")
Run Code Online (Sandbox Code Playgroud)

然后它应该按预期工作。

此外,如果它仍然无法按预期工作,我建议为每个GroupedOpenApi角色创建两个单独的角色,并通过超级角色的路径标识符(即在您的情况下)分隔 api ADMIN,并在相应的 antMatchers 上创建相应的安全配置(例如:.antMatchers("/rest/admin/**").hasAnyRole("ADMIN"))。当您在每个角色的路径上配置安全性以及为文档配置单独的 GroupedOpenApi 时,这应该可以工作。

PS:我会首先尝试第一种方法,只使用第二种方法作为后备。