将 Swagger Basic AUTH 添加到 Spring Boot App

Add Swagger Basic AUTH to Spring Boot App

请求ui评论:

代码:已实现

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/swagger-resources/*", "*.html", "/api/v1/swagger.json")
                .hasAuthority("SWAGGER")
                .anyRequest().permitAll()
            .and()
                .httpBasic()
            .and()
                .csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("admin").authorities("SWAGGER");
    }
}

但是此代码不起作用 - 您可以自由浏览 /swagger-ui.html#/ 无需任何身份验证。

问题是 - 为什么 BASIC 身份验证和用户不适用于 swagger ui 端点?

你的配置很奇怪。你可以尝试这样的事情:

public static void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
    .antMatcher("/swagger-ui.html")
    .authorizeRequests()
        .anyRequest().hasAnyRole("SWAGGER")
        .and()
    .httpBasic();
}

这确保对 swagger-ui.html 路径的授权(具有 SWAGGER 角色)。

您应该使用 .authenticated() 而不是 .permitAll():

.authorizeRequests()
    .antMatchers("/swagger-resources/*", "*.html", "/api/v1/swagger.json")
        .hasRole("SWAGGER")
    .anyRequest()
        .authenticated()

这将:

  • 限制对匹配 /swagger-resources/**.html/api/v1/swagger.json

  • 的所有资源的访问
  • 允许未经身份验证访问所有其他资源

要澄清为什么您的配置不起作用,那是因为您没有按照您应该阅读的方式阅读 spring-security。

你的旧配置是这样的:

.authorizeRequests() // allow requests
    .antMatchers(...) // that matches this
        .hasAuthority("SWAGGER") // with SWAGGER authority
    .anyRequest() // All requests above
        .permitAll() // grant full access 

换句话说,您授予具有 SWAGGER 权限的用户完全访问权限,但您忽略的是,默认情况下,他们已经可以访问它。更准确地说,每个人 都可以访问它,除非您另外指定.

通过使用 .authenticated()。您告诉 Spring 您希望所有匹配的请求仅限于具有正确 roleauthority.

的人

新配置:

.authorizeRequests() // allow requests
    .antMatchers(...) // that matches this
        .hasRole("SWAGGER") // with role SWAGGER
    .anyRequest() // all requests above
        .authenticated() // needs authentication

更新

关于 /swagger-resources/swagger-resources/configuration/securityswagger-resources/configuration/ui 返回 401 的问题:

您应该将 /swagger-resources/* 替换为 /swagger-resources/**

更新 2

在配置的 末尾 添加以下内容以允许所有不匹配的请求:

.authorizeRequests()
    .anyRequest()
        .permitAll();

你可以像下面那样做

招摇

swagger的代码如下

    private List<SecurityScheme> basicScheme() {
        List<SecurityScheme> schemeList = new ArrayList<>();
        schemeList.add(new BasicAuth("basicAuth"));
        return schemeList;
    }

    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
            .
            .
            .
            .securitySchemes(basicScheme());
    }

安全配置

对于安全配置

    public void configureGlobal(final AuthenticationManagerBuilder auth)
        throws Exception {
        auth.inMemoryAuthentication()
                .withUser("USER")
                .password("PASSWORD")
                .roles("ADMIN");
    }
    .
    .
    .
    @Override
    protected void configure(final HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests()
    .anyRequest().authenticated().and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().httpBasic();
    }
    .
    .
    .
    @Override
    public void configure(final WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs",
            "/configuration/ui",
            "/swagger-resources/**",
            "/webjars/**",
            "/configuration/security",
            "/swagger-ui.html");
    }

控制器

下面使用 swagger 将授权传递给方法。

   @PutMapping("/registration/{id}")
    @ApiOperation(value = "Update registration detail",
                  authorizations = { @Authorization(value="basicAuth") })
    public ResponseEntity<RegistrationModel> updateRegistration(

POM

在您的 pom.xml 中,您将需要:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

基本上就是这样。