如何传递由openapi-maven-generator-plugin生成的ApiClient的凭据?

huangapple go评论70阅读模式
英文:

How to pass credentials for ApiClient generated by openapi-maven-generator-plugin?

问题

我正在使用 openapi-generator-maven-plugin 从现有的 YAML 规范文件1生成一个 Java 和 SpringBoot 项目的 API 客户端。

API 端点受基本的 HTTP 安全方案(用户名和密码)保护,如下所示:

securitySchemes:
    BasicAuth:
        type: http
        scheme: basic

生成的客户端(在我的情况下是 UsersApi)带有一个 ApiClient 类,该类将使用 RestTemplate 执行所有的 REST 调用。

有没有一种方式可以将凭据传递给 ApiClient,以便我可以访问外部的 API。

英文:

I am using openapi-generator-maven-plugin to generate an api client from an existing yaml specification file in a Java and SpringBoot project .

The API endpoint are protected by Basic HTTP Security scheme (username and password) this way :

securitySchemes:
    BasicAuth:
        type: http
        scheme: basic

The generated client (UsersApi in my case) comes with an ApiClient class which will use a RestTemplate to perform all the REST calls.

Is there a way to pass the credentials to ApiClient so I will be able to reach the external API.

答案1

得分: 0

我找到的解决方案是这样注入两个类型为 UsersApiApiClient 的 bean:

@Configuration
public class ApiClientCustomConfig {

    @Value("${api.credentials.username}")
    private String username;

    @Value("${api.credentials.password}")
    private String password;


    @Bean
    @Qualifier("usersApi")
    public UsersApi usersApi(RestTemplate restTemplate) {
        return new UsersApi(apiClient(restTemplate));
    }

    @Bean
    public ApiClient apiClient(RestTemplate restTemplate) {
        ApiClient apiClient = new ApiClient(restTemplate);
        apiClient.setUsername(username);
        apiClient.setPassword(password);
        return apiClient;
    }
}
英文:

The solution that I found is to inject 2 beans of type UsersApi and ApiClient this way :

@Configuration
public class ApiClientCustomConfig {

    @Value("${api.credentials.username}")
    private String username;

    @Value("${api.credentials.password}")
    private String password;


    @Bean
    @Qualifier("usersApi")
    public UsersApi usersApi(RestTemplate restTemplate) {
        return new UsersApi(apiClient(restTemplate));
    }

    @Bean
    public ApiClient apiClient(RestTemplate restTemplate) {
        ApiClient apiClient = new ApiClient(restTemplate);
        apiClient.setUsername(username);
        apiClient.setPassword(password);
        return apiClient;
    }
}

huangapple
  • 本文由 发表于 2023年2月27日 07:52:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定