如何让OpenAPI Generator生成带Authentication参数的Spring接口?
配置OpenAPI Generator自动添加Authentication参数到Spring接口方法
方法1:自定义接口模板(最灵活可靠)
OpenAPI Generator基于Mustache模板生成代码,你可以修改接口方法模板来自动注入Authentication参数:
- 从OpenAPI Generator官方代码仓库中获取Spring接口的模板文件
api.mustache(路径通常为modules/openapi-generator/src/main/resources/JavaSpring/api.mustache) - 将模板复制到本地项目的自定义目录,比如
src/main/resources/templates/ - 修改模板中的方法参数区域,在参数列表末尾添加(或按需调整位置):
如果需要适配Spring Boot 3的注解简化,也可以改为:{{#hasParameters}}, {{/hasParameters}}org.springframework.security.core.Authentication authentication{{#hasParameters}}, {{/hasParameters}}@org.springframework.security.core.annotation.AuthenticationPrincipal org.springframework.security.core.Authentication authentication - 生成代码时指定自定义模板目录:
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规范的自定义扩展字段结合模板实现:
- 在OpenAPI规范文件的目标接口中添加扩展标记:
/username: get: x-add-auth-param: true responses: '200': description: 返回当前用户名 content: text/plain: schema: type: string - 修改自定义
api.mustache模板,添加判断逻辑:{{#x-add-auth-param}}{{#hasParameters}}, {{/hasParameters}}org.springframework.security.core.Authentication authentication{{/x-add-auth-param}} - 参考方法1的命令用自定义模板生成代码。
内容的提问来源于stack exchange,提问作者Shorn
相关产品推荐
相关产品推荐

