Swagger about token verification

Posted May 28, 20202 min read

Swagger about token verification

  1. Requirements

Microservice oauth2 verification token, configure global token parameters through Swagger2's securitySchemes, or you can create a default test user to log in to obtain a permanent period of token when the default startup.

Second, swagger configuration implementation

@Configuration
@ EnableSwagger2
public class SwaggerConfig {
   /**
     * Create a Docket object
     * Call the select() method,
     * Generate an instance of the ApiSelectorBuilder object, which is responsible for defining the leaked API entry
     * Provide Predicate by using RequestHandlerSelectors and PathSelectors, here we use any() method to manage all APIs through Swagger for document management
     *
     * @return
     * /
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                .globalOperationParameters(globalOperationParameters());
    }

    private List <Parameter> globalOperationParameters() {
        //Add default head parameter Authorization
        ParameterBuilder tokenPar = new ParameterBuilder();
        List <Parameter> pars = new ArrayList <Parameter>();
        tokenPar.name("Authorization"). defaultValue("Bearer") .description("Token"). modelRef(new ModelRef("string")). parameterType("header"). required(false) .build() ;
        pars.add(tokenPar.build());
        return pars;
    }

    private List <ApiKey> securitySchemes() {
        List <ApiKey> apiKeyList = new ArrayList();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }

    private List <SecurityContext> securityContexts() {
        List <SecurityContext> securityContexts = new ArrayList <>();
//Through PathSelectors.regex("^(?! auth). * $"), Exclude interfaces containing "auth" without using securitySchemes
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^(?! auth). * $"))
                        .build());
        return securityContexts;
    }

    List <SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope []authorizationScopes = new AuthorizationScope [1];
        authorizationScopes [0]= authorizationScope;
        List <SecurityReference> securityReferences = new ArrayList <>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //title
                .title("gold-mall-biz uses Swagger2 to build RESTful APIs")
                //Introduction
                .description("")
                //Terms of Service
                .termsOfServiceUrl("")
                //Author's personal information
                .contact(new Contact("xxx", "", "xxx@163.com"))
                //version
                .version("1.0")
                .build();
    }
}

After the setting is completed, enter SwaggerUI, the "Authorization" button appears in the upper right corner, and the input token will bring a token to the interface result containing auth except the above.

Related Posts