Swagger permission control part 1: Implementation Based on Apache Shiro

Many articles mentioned that Swagger should be turned off in the production environment to prevent system resource leakage. Today, with my own experience in the development process, I share a method that can be implemented in just a few lines of code to allow Apache Shiro to take over Swagger authentication and authorization. If there is a better way, please leave a message at the end of the article and communicate with me.

Meet Swagger

>In short, Swagger is an open source framework designed to use a common language so that both developers and non developers can understand what structure and purpose your API is designed for. API documents are like building blueprints. When building a house, you must follow the specifications of the blueprints.

Usually, a software project will be accompanied by many API documents to be written. When the software version changes, all API document details (such as request address, request parameter, return value, etc.) need to be modified. This is a very challenging job. For a long time, engineers have been trying to find a standardized process / method to solve the design, writing, testing and maintenance of API documents. Swagger was born in such a context.

Swagger provides a unified solution for the design, development, testing and maintenance of API documents. This greatly reduces the workload of developers. However, there is also a concern that providing unified API document reading and testing through the Swagger UI will lead to the exposure of system resources in the production environment. We don't want everyone to have access to the API documents of the system, just like not everyone has permission to view the architectural blueprint. So how to solve this problem?

Apache Shiro takes over Swagger authentication

Swagger officially provides six authentication and authorization methods: basic authentication, API key, bear authentication, Oauth 2.0, OpenID Connect Discovery and Cookie. However, none of these methods works well in experience (of course, you can also choose to turn off swagger in the production environment). Can there be a way for the system's own authority authentication system to take over the authorization and authentication work of swagger and let swagger focus on the field that he is good at? This is the focus of this article.

Get to know Apache Shiro quickly

Apache Shiro Gamma Is a powerful and easy-to-use Java security framework for authentication, authorization, encryption and session management. You can easily integrate it into your project without changing too much code. Shiro supports one or more pluggable data sources, such as LDAP, JDBC, Active Directory, etc. at the same time, Shiro also supports different granularity of access control, such as based on user groups, user roles, resource permissions, etc.

Use Shiro to take over Swagger certification authorization

First of all, suppose you have used Swagger in your own project, and your project is built based on Spring Boot 2.0, and Maven is used to manage project dependencies. If your project does not use Swagger, configure the following code to pom.xml In the file:

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

In addition, please check whether Shiro project dependency has been added to the project. If not, please configure the following code to pom.xml In the file:

<dependency>
    <groupid>org.apache.shiro</groupid>
    <artifactid>shiro-core</artifactid>
    <version>1.4.2</version>
</dependency>
<dependency>
    <groupid>org.apache.shiro</groupid>
    <artifactid>shiro-ehcache</artifactid>
    <version>1.4.0</version>
</dependency>
<dependency>
    <groupid>org.apache.shiro</groupid>
    <artifactid>shiro-spring</artifactid>
    <version>1.4.0</version>
</dependency>

>Remarks > >Shiro core: Apache Shiro core dependency package > >Shiro Ehcache: data cache dependency package based on Ehcache > >Shiro Spring: Apache Shiro and Spring integrate dependency package

Configure Swagger

After the dependency is ready, create a configuration file of Swagger and set the package path (usually the package where the Controller is located), API document title, description, version, contact information, certificate name, etc. that Swagger will scan. The following is an example of a Swagger configuration file:

SwaggerConfiguration.java

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.ramostear.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(
                        new ApiInfoBuilder()
                        .title("Apache Shiro &amp; Swagger")
                        .description("use Apache Shiro take over Swagger Certification and authorization")
                        .version("1.0.0")
                        .contact(
                                new Contact("Fox under the tree",
                                        "https://www.ramostear.com",
                                        "ramostear@163.com")
                        )
                        .license("The Apache License")
                        .build()
                );
    }
}

>Attention > >In addition to using @ Configuration to annotate the Configuration class, do not omit the @ EnableSwagger annotation!

Configuring Swagger in Shiro

If your project has used Apache Shiro for authentication and authorization, you only need to add the filtering operation to Swagger in the configuration code of ShiroFilterFactoryBean. You can refer to the following code for configuration:

ShiroConfiguration.java

@Configuration
public class ShiroConfiguration{
    
    @Bean
    public EhCacheManager ehCacheManager(){...}
    
    @Bean
    public CustomShiroRealm customShiroRealm(){...}
    
    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setCacheManager(ehCacheManager());
        securityManager.setRealm(customShiroRealm());
        return securityManager;
    }
    ...
    
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);
        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;     
    }
    ....
}

>Supplement > >In addition to the above configuration mode, you can configure more fine-grained permissions, such as user groups, roles, resource permissions, etc. according to actual needs.

So far, if you originally used the Apache Shiro framework for your project, just add three lines of configuration code on the basis of the original code to let Apache Shiro take over the authentication and authorization work of Swagger.

Finally, the effect of Apache Shiro taking over Swagger authentication and authorization is demonstrated through a real project:

>Description > >The / admin / swagger request page has an iframe embedded at the address of: / swagger-ui.html . The specific code is as follows: > > swagger.html > > html &gt; &gt; &gt; ... &gt; &gt; &gt; ... &gt; <iframe src="./swagger-ui.html" frameborder="0" scrolling="auto"></iframe> &gt; ... &gt; &gt; &gt; > >

After the user logs in successfully, he / she can normally visit the API document page of Swagger. After logging out of the current user, he / she can visit the Swagger page again, and the system will jump to the user log in page to verify the user's identity.

</string,string>

Tags: Programming Shiro Apache Spring Java

Posted on Fri, 22 May 2020 03:11:03 -0400 by K3nnnn