Java Swagger如何配置自动为Authorization头添加Bearer/ApiKey前缀
原生ApiKey配置默认不会自动添加Bearer/ApiKey这类方案前缀,你可以按以下方式修改配置实现需求:
方案1:使用HttpAuthenticationScheme(推荐,SpringFox 2.9.0及以上版本支持)
直接替换你原有的ApiKey配置即可,无需修改其他逻辑:
- 如需
Bearer前缀,配置如下:
private HttpAuthenticationScheme getBearerScheme() { return HttpAuthenticationScheme.JWT_BEARER_BUILDER .name("BearerAuth") .scheme("Bearer") .bearerFormat("JWT") .build(); }
- 如需自定义
ApiKey前缀,配置如下:
private HttpAuthenticationScheme getCustomApiKeyScheme() { return HttpAuthenticationScheme.BASIC_AUTH_BUILDER .name("ApiKeyAuth") .scheme("ApiKey") .build(); }
然后修改Docket中的securitySchemes配置为对应的实现即可:
.securitySchemes(Collections.singletonList(getBearerScheme())) // 替换为你需要的方案方法
方案2:低版本SpringFox兼容方案
如果你使用的SpringFox版本低于2.9.0,不支持HttpAuthenticationScheme,可以通过添加全局请求参数的方式实现:
private Parameter buildAuthHeader() { return new ParameterBuilder() .name("Authorization") .modelRef(new ModelRef("string")) .parameterType("header") .defaultValue("Bearer <输入你的令牌>") // 前缀可自定义为ApiKey .required(false) .build(); }
在Docket配置中添加全局参数:
Docket docket = new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("mypackagename")) .build() .useDefaultResponseMessages(false) .apiInfo(metaData()) .globalOperationParameters(Collections.singletonList(buildAuthHeader())) // 新增该配置 .securityContexts(Collections.singletonList(securityContext()));
内容的提问来源于stack exchange,提问作者Emin Bilgic
相关产品推荐
相关产品推荐

