You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Swagger如何配置自动为Authorization头添加Bearer/ApiKey前缀

Swagger Java 配置Authorization头自动携带前缀方案

原生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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 06:54:04