简体   繁体   English

将 Swagger Basic AUTH 添加到 Spring Boot 应用程序

[英]Add Swagger Basic AUTH to Spring Boot App

Requirements:要求:

  • Spring Boot application with Springfox带有 Springfox 的 Spring Boot 应用程序
  • Add BASIC authentication to Swagger向 Swagger 添加 BASIC 身份验证
  • Pass on all other requests传递所有其他请求

Code: implemented代码:已实现

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

This code however does not work - you can freely browse /swagger-ui.html#/ without any authentcation.但是,此代码不起作用 - 您可以在没有任何身份验证的情况下自由浏览 /swagger-ui.html#/。

Question is - why BASIC auth and user do not apply to swagger ui endpoint?问题是 - 为什么 BASIC auth 和 user 不适用于 swagger ui 端点?

You should use the .authenticated() instead of .permitAll() :您应该使用.authenticated()而不是.permitAll()

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

This will:这会:

  • Restrict access to all resources matching /swagger-resources/* , *.html and /api/v1/swagger.json限制访问所有匹配/swagger-resources/**.html/api/v1/swagger.json

  • Allow unauthenticated access to all other resources允许未经身份验证访问所有其他资源

For clarification on why your configuration doesn't work, it's because you're not reading spring-security like you should be reading it.为了澄清为什么您的配置不起作用,这是因为您没有像您应该阅读的那样阅读 spring-security 。

Your old configuration reads like this:您的旧配置如下所示:

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

In other words, you're granting full access to users with the SWAGGER authority, but what you've neglected is that by default, they already have access to it.换句话说,您授予具有SWAGGER权限的用户完全访问权限,但您忽略了默认情况下,他们已经可以访问它。 To be more precise, everybody has access to it unless you specify otherwise .更准确地说,除非您另有说明,否则每个人都可以访问它

By using .authenticated() .通过使用.authenticated() you're telling Spring that you want all requests matched to be restricted to people with the proper role or authority .您告诉 Spring 您希望所有匹配的请求仅限于具有适当roleauthority

New configuration:新配置:

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

Update更新

Regarding your issue with /swagger-resources , /swagger-resources/configuration/security and swagger-resources/configuration/ui returning 401:关于/swagger-resources/swagger-resources/configuration/securityswagger-resources/configuration/ui返回 401 的问题:

You should replace /swagger-resources/* for /swagger-resources/** .您应该将/swagger-resources/*替换为/swagger-resources/**

Update 2更新 2

Add the following at the end of your configuration to permit all non-matched requests:在配置末尾添加以下内容以允许所有不匹配的请求:

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

You could do something like below你可以做类似下面的事情

Swagger昂首阔步

The code for swagger is like below. 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());
    }

Security Config安全配置

For the security config对于安全配置

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

Controllers控制器

Below passes the authorization to the methods using swagger.下面使用 swagger 将授权传递给方法。

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

POM聚甲醛

and in your pom.xml, you will be needing:在你的 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>

That's basically it.基本上就是这样。

Your configuration is strange.你的配置很奇怪。 You can try something like that:你可以尝试这样的事情:

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

This ensures authorization to swagger-ui.html path (with SWAGGER role).这确保了对swagger-ui.html路径的授权(具有SWAGGER角色)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM