2

问题: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添加
image.png


一片秋叶一树春
47 声望3 粉丝

贪君子之财,好美景之色,行正义之事,了前生之愿,爱此生之人!!!!!