如何配置OpenAPI生成的多Micronaut声明式客户端的认证?
配置Micronaut OpenAPI生成客户端的独立基础认证
1. 确定目标客户端的Client ID
生成的声明式客户端类上会带有@Client注解,注解内的值就是该客户端的唯一标识(Client ID)。比如生成的WeatherApiClient类可能会有:
@Client("weather-api") public interface WeatherApiClient { // 接口方法 }
这里的weather-api就是你需要在配置中使用的Client ID。如果注解没有指定值,默认会使用OpenAPI Spec中info.title的小写横线分隔形式(比如Weather API会变成weather-api)。
2. 针对单个客户端配置基础认证
在application.yml或application.properties中,通过micronaut.http.client.<client-id>.auth前缀为指定客户端单独配置基础认证:
YAML配置示例:
micronaut: http: client: weather-api: # 替换为你的Client ID auth: basic: username: your-username password: your-password url: https://api.open-meteo.com/ # 单个客户端的基础路径(可覆盖全局配置)
Properties配置示例:
# 基础认证配置 micronaut.http.client.weather-api.auth.basic.username=your-username micronaut.http.client.weather-api.auth.basic.password=your-password # 单个客户端的基础路径 micronaut.http.client.weather-api.url=https://api.open-meteo.com/
3. 多客户端独立配置
每个客户端对应不同的Client ID,分别配置即可实现各自独立的认证和路径:
micronaut: http: client: weather-api: auth: basic: username: weather-service-user password: weather-service-pass url: https://api.open-meteo.com/ payment-api: auth: basic: username: payment-service-user password: payment-service-pass url: https://api.payment-provider.com/
4. 关键注意事项
- 如果在OpenAPI Generator的Maven配置中指定了
clientId参数,需确保配置中的Client ID与该参数值完全一致。 - 全局的
openapi-micronaut-client-base-path会被单个客户端的url配置覆盖,优先使用客户端专属路径。 - 敏感的用户名/密码建议通过环境变量注入,比如
username: ${WEATHER_API_USERNAME:default-user},避免硬编码在配置文件中。
内容的提问来源于stack exchange,提问作者wolle
相关产品推荐
相关产品推荐

