Apache Shiro takes over Swagger authentication and Authorization Personally, I do not make any comments on this issue (all technologies serve the needs). How to take over Swagger’s authentication and authorization under Spring Security

1. Add dependencies

Assuming you already have some foundation in Swagger and Spring Security, now check to see if you have Swagger and Spring Security dependencies added to your project. Using Maven as an example, add the following configuration information to the pom. XML 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>
Copy the code

2. Configuration Swagger

The configuration of Swagger is relatively simple. The most important thing is to configure the packet path that Swagger scans. Other information can be optional. You can configure it as follows:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket docket(a){
        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 takes over Swagger Authentication and Authorization)
                    .description("Spring Security and Swagger")
                    .version("1.0.0")
                    .contact(
                        new Contact(
                            "The Fox under the Tree."."https://www.ramostear.com"."[email protected]") ).build() ); }}Copy the code

The configuration of Swagger is basically the same as 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 two login accounts 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 (omit the account configuration if you have already configured Spring Security and obtained login account information based on JDBC).

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(a){
        return newBCryptPasswordEncoder(); }}Copy the code

In the configuration class, the AUTH_LIST array holds the URL that Swagger needs to add to Spring Security authentication:

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

This is exactly the same as in Apache Shiro.

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

The key to Spring Security taking over Swagger authentication is the configure(HttpSecurity HTTP) method:

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

Simply add Swagger’s related URLs to Spring Security’s certified filter chain. When unauthorized users access to Swagger document (http://localhost:8080/swagger-ui.html), the page will jump to the user login page.

4. Test

Now, start the application, and in your browser’s address bar: http://localhost:8080/swagger-ui.html. After you press Enter, the login page is displayed.

Next, log in using the previously configured account and password (user name: user, password: password). After successful login, you can browse Swagger document page information.

You can get a better understanding of the testing process through the following dynamic pictures:

5. To summarize

This article describes how to use Spring Security to take over Swagger’s default authentication under Spring Boot. By managing Swagger authentication and authorization with Apache Shiro, you can see that Spring Security and Apache Shiro basically manage Swagger’s permission logic by adding Swagger’s URLs to their authentication and authorization filtering chains. When a user accesses Swagger’s resource, both Apache Shiro and Spring Security check the current request path (including whether the user is logged in and whether the current user has permission to access the URL).