How to configure swagger with shiro

Keywords: Java Shiro Spring Apache github

In order to save the time and cost of developers, swagger plug-ins arise spontaneously, save your time to write development documents, and play happily, without talking nonsense. Next I will explain and explain using the popular swagger-bootstrap-ui plug-in on github, which may be different from swagger in configuration, but the principle is bad, but only in resource filtering. Different, especially when combined with filtering spring security or shiro.

Add dependency

<properties>
        <java.version>1.8</java.version>
        <shiro.version>1.4.0</shiro.version>
        <swagger2.version>2.9.2</swagger2.version>
    </properties>
<!--swagger api File start-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger2.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
                <!--<exclusion>-->
                <!--<artifactId>guava</artifactId>-->
                <!--<groupId>com.google.guava</groupId>-->
                <!--</exclusion>-->
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.0</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
            <exclusions>
                <exclusion>
                    <artifactId>swagger-annotations</artifactId>
                    <groupId>io.swagger</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--shiro Security framework start-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>${shiro.version}</version>
        </dependency>

swagger combined with shiro code analysis

Since spring defaults to open resource files (such as images and html files), we need to add a configuration class to make it open:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.servlet.ServletContext;


@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    //  Please add this property to the properties file to determine whether swagger is turned on or not.
    @Value("${swagger.enable}")
    private boolean swaggerEnable;

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/logo.png")
                .addResourceLocations("classpath:/");
        registry.addResourceHandler("/favicon.ico")
                .addResourceLocations("classpath:/");
        // Determine whether the swagger document interface is enabled, which opens up these resources for developers to access
        if (swaggerEnable) {
            registry.addResourceHandler("/doc.html")
                    .addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**")
                    .addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
        super.addResourceHandlers(registry);
    }

    @SuppressWarnings({"unchecked"})
    @Bean
    public FilterRegistrationBean normalCorsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // Set the domain name of the website you want to allow, and if it's all allowed, set it to _________.*
        config.addAllowedOrigin("*");
        // If you want to restrict HEADER or METHOD, please change it yourself
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        // This order is very important. To avoid trouble, please set it at the front.
        bean.setOrder(0);
        return bean;
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        servletContext.setSessionTimeout(12*60*60);
        super.setServletContext(servletContext);
    }
}
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


/**
 * Use only in test and development environments
 * @author Anthony
 */
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@Profile({"dev", "test"}) // When you have multiple properties profiles, add
public class SwaggerConfiguration {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
.apis(RequestHandlerSelectors.basePackage("com.shiro.demo.CRUD.controller")) // The last one is the location of your Controller package.
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("shiro Authority control")
                .description("restful style")
                .version("1.0")
                .build();
    }
}

Since I'm learning Shiro recently, I'll explain the use of swagger on the basis of shiro. The next step is to prevent Shiro from filtering the configuration of swagger files. If you don't use Shiro or spring security, please ignore it. Thank you.

 /** Create a configuration class, create a bean called shiroFilter, which is shiro's filter configuration class, set the corresponding filter conditions and jump conditions, I just write swagger files that do not need Shiro filter.**/
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// Configuration will not be intercepted link order judgment
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        //Release of swagger resources intercepted by shiro
        filterChainDefinitionMap.put("/doc.html/**", "anon");
        filterChainDefinitionMap.put("/swagger-resources/**", "anon");
        filterChainDefinitionMap.put("/v2/api-docs/**", "anon");
        filterChainDefinitionMap.put("/webjars/**", "anon");
        filterChainDefinitionMap.put("/swagger-resources/configuration/ui/**", "anon");
        filterChainDefinitionMap.put("/swagger-resources/configuration/security/**", "anon");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}

swagger-bootstrap-ui is an interface document plug-in that integrates swagger and extends it. It is recommended to use it.
Effect demonstration:

This article focuses on the combination of shiro and swagger. Next, I will introduce the simple application of native swagger.

Posted by trex005 on Sun, 06 Oct 2019 02:10:47 -0700