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

如何让OpenAPI Generator生成带Authentication参数的Spring接口?

配置OpenAPI Generator自动添加Authentication参数到Spring接口方法

方法1:自定义接口模板(最灵活可靠)

OpenAPI Generator基于Mustache模板生成代码,你可以修改接口方法模板来自动注入Authentication参数:

  1. 从OpenAPI Generator官方代码仓库中获取Spring接口的模板文件api.mustache(路径通常为modules/openapi-generator/src/main/resources/JavaSpring/api.mustache)
  2. 将模板复制到本地项目的自定义目录,比如src/main/resources/templates/
  3. 修改模板中的方法参数区域,在参数列表末尾添加(或按需调整位置):
    {{#hasParameters}}, {{/hasParameters}}org.springframework.security.core.Authentication authentication
    
    如果需要适配Spring Boot 3的注解简化,也可以改为:
    {{#hasParameters}}, {{/hasParameters}}@org.springframework.security.core.annotation.AuthenticationPrincipal org.springframework.security.core.Authentication authentication
    
  4. 生成代码时指定自定义模板目录:
    openapi-generator generate -i your-openapi-spec.yaml -g spring \
      --template-dir src/main/resources/templates \
      --additional-properties=interfaceOnly=true
    

方法2:使用全局配置参数(快速实现)

如果不想修改模板,可以通过additional-properties全局参数直接注入方法参数,建议使用v6.0+版本的OpenAPI Generator以确保兼容性:

openapi-generator generate -i your-openapi-spec.yaml -g spring \
  --additional-properties=additionalMethodParameters=org.springframework.security.core.Authentication authentication,interfaceOnly=true

方法3:针对单个接口按需配置

如果仅需给特定接口添加参数,可以通过OpenAPI规范的自定义扩展字段结合模板实现:

  1. 在OpenAPI规范文件的目标接口中添加扩展标记:
    /username:
      get:
        x-add-auth-param: true
        responses:
          '200':
            description: 返回当前用户名
            content:
              text/plain:
                schema:
                  type: string
    
  2. 修改自定义api.mustache模板,添加判断逻辑:
    {{#x-add-auth-param}}{{#hasParameters}}, {{/hasParameters}}org.springframework.security.core.Authentication authentication{{/x-add-auth-param}}
    
  3. 参考方法1的命令用自定义模板生成代码。

内容的提问来源于stack exchange,提问作者Shorn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:40:37