英文:
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
我找到的解决方案是这样注入两个类型为 UsersApi 和 ApiClient 的 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;
    }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论