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

@ 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
     * /
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)

    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() ;
        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
                        .forPaths(PathSelectors.regex("^(?! auth). * $"))
        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("gold-mall-biz uses Swagger2 to build RESTful APIs")
                //Terms of Service
                //Author's personal information
                .contact(new Contact("xxx", "", "xxx@163.com"))

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