将Swagger Basic AUTH添加到Spring Boot App

时间:2018-04-25 14:02:30

标签: java spring spring-boot swagger springfox

要求:

  • 使用Springfox的Spring Boot应用程序
  • 向Swagger添加BASIC身份验证
  • 传递所有其他请求

代码:已实施

@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 auth和用户不适用于swagger ui端点?

3 个答案:

答案 0 :(得分:3)

您应该使用.authenticated()代替.permitAll()

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

这将:

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

  • 匹配的所有资源的访问权限
  • 允许对所有其他资源进行未经身份验证的访问

为了澄清您的配置无法正常工作的原因,这是因为您没有阅读弹簧安全性,就像您应该阅读它一样。

您的旧配置如下所示:

.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();

答案 1 :(得分:1)

您可以执行以下操作

昂首阔步

摇摇欲坠的代码如下。

    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");
    }

控制器

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

   @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>

基本上就是这样。

答案 2 :(得分:0)

您的配置很奇怪。你可以试试这样的东西:

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角色)。

相关问题