SpringBoot e-commerce project mall (40K + STAR) address: github.com/macrozheng/…

Abstract

In the previous project, Swagger was integrated directly by relying on springfox-Swagger and Springfox-Swagger UI jar packages. Recently, it was found that SpringFox 3.0.0 has its own SpringBoot Starter. Use more suitable for SpringBoot project, very convenient, recommended to everyone!

Use the official Starter

Let’s use the official Starter to integrate Swagger and see if it’s easy enough!

  • First of all inpom.xmlAdd springFox official Swagger dependency;
<! Springfox Swagger Starter-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
Copy the code
  • Add Swagger Java configuration, configure Api information and class scan path that need to generate interface document.
/** * Swagger2API file configuration */
@Configuration
public class Swagger2Config {
    @Bean
    public Docket createRestApi(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                .title("SwaggerUI demonstration")
                .description("mall-tiny")
                .contact(new Contact("macro".null.null))
                .version("1.0") .build(); }}Copy the code
  • Access API document information, access to the address: http://localhost:8088/swagger-ui/

  • SpringBoot integrated Swagger in two steps, isn’t it easy?

Compared to previous versions

Previously we used SpringFox version 2.9.2, now compare the use of SpringBoot Starter 3.0.0 to see the difference!

  • Older versions require dependenciesspringfox-swagger2andspringfox-swagger-uiTwo configurations, a Starter for the new version, and if the previous version does not use the new versionswagger-modelsandswagger-annotationsDependency, the access interface will appearNumberFormatExceptionProblem;
<dependencies>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <exclusions>
            <exclusion>
                <groupId>io.swagger</groupId>
                <artifactId>swagger-annotations</artifactId>
            </exclusion>
            <exclusion>
                <groupId>io.swagger</groupId>
                <artifactId>swagger-models</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
    </dependency>
    <! NumberFormatException-->
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-models</artifactId>
        <version>1.6.0</version>
    </dependency>
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>1.6.0</version>
    </dependency>
</dependencies>
Copy the code
  • The new version removes some third-party dependencies, including Guava, which caused dependency conflicts when using the old version. For details, see “Upgrade Swagger to a new version, I didn’t expect so many bugs!” ;

  • The new version and old version document access path has changed, the new version is: http://localhost:8088/swagger-ui/, the old version is: http://localhost:8088/swagger-ui.html

  • In the new version has added some SpringBoot configuration, springfox. Documentation. The enabled configuration can control whether to enable Swagger document generation function;

  • Let’s say we just want to bedevEnvironment enables Swagger document while inprodIf you don’t want to enable it in the environment, we can pass the old version@ProfileAnnotation implementation;
@Configuration
@EnableSwagger2
@Profile(value = {"dev"})
public class Swagger2Config {}Copy the code
  • We can configure the new version in the SpringBoot configuration file,springfox.documentation.enabledinapplication-dev.ymlSet to true, inapplication-prod.ymlIs set to false.

Integrate Spring Security usage

We often use Spring Security to implement login authentication in our projects. Now let’s talk about how to use Swagger to integrate Spring Security and access interfaces that require login authentication.

  • How do I access an interface that requires login authentication? Just add a legal one when accessing the interfaceAuthorizationRequest header is ok, below is Swagger related configuration;
/** * Swagger2API file configuration */
@Configuration
public class Swagger2Config {
    @Bean
    public Docket createRestApi(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))
                .paths(PathSelectors.any())
                .build()
                // Add login authentication
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                .title("SwaggerUI demonstration")
                .description("mall-tiny")
                .contact(new Contact("macro".null.null))
                .version("1.0")
                .build();
    }

    private List<SecurityScheme> securitySchemes(a) {
        // Set the request header information
        List<SecurityScheme> result = new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization"."Authorization"."header");
        result.add(apiKey);
        return result;
    }

    private List<SecurityContext> securityContexts(a) {
        // Set the path for login authentication
        List<SecurityContext> result = new ArrayList<>();
        result.add(getContextByPath("/brand/.*"));
        return result;
    }

    private SecurityContext getContextByPath(String pathRegex) {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(pathRegex))
                .build();
    }

    private List<SecurityReference> defaultAuth(a) {
        List<SecurityReference> result = new ArrayList<>();
        AuthorizationScope authorizationScope = new AuthorizationScope("global"."accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        result.add(new SecurityReference("Authorization", authorizationScopes));
        returnresult; }}Copy the code
  • We need to configure unauthorised access to Swagger static resources in Spring Security, such as the home page access path/swagger-ui/;
/** * Created by macro on 2018/4/26. */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UmsAdminService adminService;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf()// Since we are using JWT, we do not need CSRF here
                .disable()
                .sessionManagement()// Token-based, so no session is required
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, // Allow unauthorized access to static resources on the site
                        "/"."/swagger-ui/"."/*.html"."/favicon.ico"."/**/*.html"."/**/*.css"."/**/*.js"."/swagger-resources/**"."/v2/api-docs/**"
                )
                .permitAll()
                .antMatchers("/admin/login")// Allow anonymous access to login registrations
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)// Cross-domain requests start with an options request
                .permitAll()
                .anyRequest()// All requests other than the above require authentication
                .authenticated();
        // Omit several configurations......}}Copy the code
  • Invoke the login interface to obtain the token. The account password isadmin:123456;

  • Click on theAuthorizeInput after buttonAuthorizationRequest header, after which you can access the interface that requires login authentication.

conclusion

The Swagger official Starter solves a series of previous problems in integrating Swagger, simplifying the process of integrating Swagger by SpringBoot and making it more convenient to use. At the same time for some complex configuration use basic no change, some of the previous use can still be used!

Project source code address

Github.com/macrozheng/…

In this paper, making github.com/macrozheng/… Already included, welcome everyone Star!