关于java:swagger配置全局token

59次阅读

共计 1533 个字符,预计需要花费 4 分钟才能阅读完成。

问题:swagger 上配置全局 token,防止每次 try out 都须要在 header 中填 token 的内容
解决:
1. 配置 swagger

增加 pom 坐标
    <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>
减少 swagger 的配置类,加上注解
@Configuration
@EnableSwagger2

增加 bean
 @Bean
    public Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2)
//                .host("114.247.181.27:8888")
                .apiInfo(apiInfo())
                .select()
// 指定 controller 所在包门路   .apis(RequestHandlerSelectors.basePackage("com.screen.controller"))
                .paths(PathSelectors.any())
//              .build();
                .build()
//  平安上下文
.securityContexts(Arrays.asList(securityContexts()))
                .securitySchemes(unifiedAuth());
    }

#配置 swagger 上文档信息
  private ApiInfo apiInfo() {return new ApiInfoBuilder()
                .title("服务端 Api 接口文档")
                .description("服务端所有接口文档在此保护")
                .termsOfServiceUrl("")
                .version("2.2.0")
                .build();}

2. 增加配置全局 token

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

    private SecurityContext securityContexts() {return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.any())
                .build();}

    private List<SecurityReference> defaultAuth() {AuthorizationScope authorizationScope = new AuthorizationScope("global", "形容信息");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Arrays.asList(new SecurityReference("Authorization", authorizationScopes));
    }

3. 配置完的 token 增加

正文完
 0