SoFunction
Updated on 2025-03-03

SpringBoot Integration Swagger Use SpringSecurity to Control Access Permissions Issues

1. Join swagger dependencies

This is the Maven dependency configuration that adds Swagger.

Adding the above two dependencies to the project's file can use Swagger.

Among them, springfox-swagger2 is the core dependency of the Swagger API, and springfox-swagger-ui is Swagger's UI dependency.

 		 <dependency><!--Add toSwaggerrely -->
            <groupId></groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency><!--Add toSwagger-UIrely -->
            <groupId></groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

2. Write swagger configuration class

This is a Swagger configuration class, which uses the @Configuration annotation of Spring Boot, indicating that this is a configuration class, which uses the @EnableSwagger2 annotation to enable Swagger2, and then defines a bean named customDocket, returning a Docket object, with two attributes apiInfo and select.

  • The apiInfo method returns an ApiInfo object that is used to set the documentation and version description.
  • The select method returns an ApiSelectorBuilder object, setting the scanned package path.

All API interfaces under the scan package are set here.

@Configuration //Declare this class as a configuration class@EnableSwagger2 //Declare to start Swagger2public class SwaggerConfig{
    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis((""))//Scanned package path                .build();
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("oneclick")//Document description                .version("1.0.0")//Document version description                .build();
    }
}

3. Write SpringSecurity configuration class

Release swagger access to resource interface

This code uses Spring Security to configure security, allowing Swagger to access the resource interface without authentication and authorization.

It is used()To control access permissions, set some access addresses without authentication, such as/, /v2/**, /swagger-resources/**etc.

At the same time, some static header information is also set, such asAccess-Control-Allow-Origin, Access-Control-Expose-Headersetc.

Finally, bypermissiveRequestUrls()The method sets the unauthorized interface.

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ()
                .antMatchers("/login").anonymous()
                .antMatchers("/user/register").anonymous()
                .antMatchers("/user/sendEmailCode").anonymous()
                .antMatchers("/user/sendEmailRegisterCode").anonymous()
                .antMatchers("/").anonymous()
                .antMatchers("/v2/**").anonymous()
                .antMatchers("/swagger-resources/**").anonymous()
                .antMatchers("/webjars/springfox-swagger-ui").anonymous()
                .antMatchers("/webjars/springfox-swagger-ui/**").anonymous()
                .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .formLogin().disable()
                .sessionManagement().disable()
                .cors()
                .and()
                .headers().addHeaderWriter(new StaticHeadersWriter((
                new Header("Access-Control-Allow-Origin", "*"),
                new Header("Access-Control-Expose-Headers", "Authorization"))))
                .and()
                .addFilterAfter(new OptionsRequestFilter(), )
                .apply(new JsonLoginConfigurer<>()).loginSuccessHandler(jsonLoginSuccessHandler)
                .and()
                .apply(new JwtLoginConfigurer<>()).tokenValidSuccessHandler(jwtRefreshSuccessHandler)
                //Set the unauthorized interface                .permissiveRequestUrls("/login","/user/register","/user/sendEmailCode",
                        "/user/sendEmailRegisterCode","/","/swagger-resources/**",
                        "/v2/**","/webjars/springfox-swagger-ui/**","/webjars/springfox-swagger-ui")
                .and()
                .logout()
                .logoutUrl("/logout")
                .addLogoutHandler(tokenClearLogoutHandler)
                .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
                .and()
                .sessionManagement().disable();
    }

4. Start the project and access the swagger address

Access can skip Spring Security's access control and access Swagger document resources.

http://localhost:8081/

You can skip springsecurity to access swagger.

Summarize

This article mainly introduces how to use Swagger in Spring Boot project, and solves the problem of accessing Swagger resources when using Spring Security.

First, we need toAdd dependencies for Swagger and Swagger UI.

Then, use it in the configuration class@EnableSwagger2Enable Swagger and pass@BeanAnnotation creates aDocketObject to configure Swagger, including documentation description and scanned package paths.

In projects using Spring Security, since Spring Security protects all resources by default, we need to passWebSecurityConfigClassicconfigureMethod to let Swagger access the resource interface.

Specifically, we need to add the Swagger resource to the whitelist of Spring Security so that it can be accessed anonymously.

The specific implementation method is through()Method to authorize configuration and addantMatchers()Method matches Swagger-related resources and then callsanonymous()Methods add it to the whitelist.

Finally, we need to add aJwtLoginConfigurerObject and set up permissionless interfaces to ensure access to Swagger.

Through the above steps, we can successfully use Swagger in Spring Boot project and solve the problem of accessing Swagger resources when using Spring Security.

Anyway:

Swagger is a very useful API document generation tool, which can conveniently display API documents and test interfaces to improve development efficiency.

In actual development, we can configure Swagger as needed and ensure the interface security by integrating Spring Security.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.