Swagger 添加统一头部

2020年02月13日 139点热度 0人点赞 0条评论
    @Bean
    public Docket docket() {
        List<Parameter> parameters = new ArrayList<>();
        parameters.add(new ParameterBuilder()
                .name("X-SZ-TOKEN")
                .description("用户登录后所获取的token值")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build()
        );

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.likole.sizheng.questionnaire.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(parameters);
    }

这种方式每个接口都需要填写header,还有一种方法只需要填写一次。

    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.likole.sizheng.reservation.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(Collections.singletonList(new ApiKey("Token", "X-SZ-TOKEN", "header")))
                .securityContexts(Collections.singletonList(SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.any()).build()));

    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Collections.singletonList(new SecurityReference("Token", authorizationScopes));
    }

有一个要注意的是,ApiKey() 中的name要与SecurityReference() 中reference要对应,一开始一直无效,后来才发现问题出在这儿

likole

人能常清静,天地悉皆归

文章评论