Swagger中添加Authorization请求头需要配置securitySchemes和securityContexts。
@Configuration@EnableSwagger2public class Swagger2Config { @Bean public Docket docket() { return new Docket(DocumentationType.SWAGGER_2) .groupName("demo") .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.regex("/api/.*")) .build() # 增加Authorization请求头 .securitySchemes(securitySchemes()) .securityContexts(securityContexts()); } private List securitySchemes() { List apiKeys = new ArrayList<>(); apiKeys.add(new ApiKey("Authorization", "Authorization", "header")); return apiKeys; } private List securityContexts() { List securityContexts = new ArrayList<>(); securityContexts.add(SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("^(?!auth).*$")).build()); return securityContexts; } private List defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; List securityReferences = new ArrayList<>(); securityReferences.add(new SecurityReference("Authorization", authorizationScopes)); return securityReferences; }}
版权声明:本文为weixin_35656580原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。