Swagger permission control part 2: Implementation Based on Spring Security

Keywords: Programming Spring Apache Shiro Maven

>Following the previous article "Apache Shiro takes over the authentication and authorization of Swagger", some enthusiastic netizens said that Apache Shiro seems too simple. In response to this problem, the individual does not make any evaluation (all technologies serve the needs). Today's main share is: how to take over the authentication and authorization work of Swagger under Spring Security.

1. Add dependency

Assuming that you already have some foundation for Swagger and Spring Security, now check whether you have added the dependency of Swagger and Spring Security to your project. Take Maven, for example pom.xml Add the following configuration information to the file:

<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. Configure Swagger

The configuration of Swagger is relatively simple. The most important thing is to configure the package path for scanning. Other information can be selected. You can configure it as follows:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(
            RequestHandlerSelectors.basePackage("com.ramostear.apisecurity.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(
                    new ApiInfoBuilder()
                    .title("Spring Security take over Swagger Authentication authorization")
                    .description("Spring Security and Swagger")
                    .version("1.0.0")
                    .contact(
                        new Contact(
                            "Fox under the tree",
                            "https://www.ramostear.com",
                            "ramostear@163.com"
                        )
                    ).build()
                );
    }
}

>The configuration of swagger is basically the same as that in the previous article, except that the path of basePackage is adjusted.

3. Configure Spring Security

The configuration of Spring Security is the focus of this article. First, set up two accounts for login based on memory, and then add Swagger's resource path to Spring Security's Authorize Filters. Create the Spring Security configuration class and add the following code (if you have configured Spring Security and obtained the login account information based on JDBC, you can omit the account configuration).

SpringSecurityConfiguration.java

@Configuration
@EnableWebSecurity
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_LIST = {
      "/v2/api-docs",
      "/configuration/ui",
      "/swagger-resources/**",
      "/configuration/security",
      "/swagger-ui.html",
      "/webjars/**"
    };


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .passwordEncoder(passwordEncoder())
            .withUser("user")
            .password(passwordEncoder().encode("password"))
            .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers(AUTH_LIST)
            .authenticated()
            .and()
            .formLogin()
            .and()
            .httpBasic();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

In the configuration class, auth_ The list array holds the URL that Swagger needs to join Spring Security authentication:

private static final String[] AUTH_LIST = {
      "/v2/api-docs",
      "/swagger-resources/**",
      "/swagger-ui.html",
      "/webjars/**"
    };

This is the same as the configuration in Apache Shiro. Here is the code for configuring Swagger in Apache Shiro:

@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
    ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
    Map<string,string> filterChainDefinition = new LinkedHashMap&lt;&gt;();
    filterChainDefinition.put("/swagger-ui.html","authc");
    filterChainDefinition.put("/v2/**","authc");
    filterChainDefinition.put("/swagger-resources/**","authc");
    filterFactoryBean.setFilterChainDefinitionMap(filterChainDefinition);
    return filterFactoryBean;
}

The core to let Spring Security take over the authentication and authorization of Swagger is the configure(HttpSecurity http) method:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers(AUTH_LIST)
        .authenticated()
        .and()
        .httpBasic();
}

Simply add the relevant URLs of Swagger to the Spring Security authentication filter chain. When an unauthenticated user accesses a Swagger document( http://localhost:8080/swagger-ui.html ), the page will jump to the user login page.

4. Test

Now start the application and enter: http://localhost:8080/swagger-ui.html . Press enter and the page will jump to the login page.

Next, log in using the previously configured account and password (user name: user, password: password). Once you have successfully logged in, you can browse the Swagger documentation page information.

With the following dynamic pictures, you can understand the test process more intuitively:

5. Summary

This article describes in detail how to use Spring Security to take over Swagger's default authentication work under Spring Boot. Through the authentication and authorization with Apache Shiro to manage Swagger, we can find that the logic of Spring Security and Apache Shiro to manage Swagger permissions is basically the same, that is, adding the URLs of Swagger to their respective authentication and authorization filter chains. When users access the resources corresponding to Swagger, Apache Shiro and Spring Security checks the current request path (including whether the user is logged in and whether the current user has access to the url).

</string,string>

Posted by Chrisinsd on Fri, 22 May 2020 00:13:44 -0700