How to add basic-auth with user and password in org.openapitools.client.ApiClient

Viewed 233

I used this openapigenerator https://openapi-generator.tech/docs/generators/java to generate a java client-app , so this create an ApiClient class, so with this class I create a request; in the example code it shows this:

import org.openapitools.client.api.WorkspaceApi;
import org.openapitools.client.model.WorkspaceReadList;

public class App {

    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();
        defaultClient.setBasePath("http://serveprodhost/api");
        System.out.println(defaultClient.getAuthentications());

        WorkspaceApi apiInstance = new WorkspaceApi(defaultClient);
        try {
            WorkspaceReadList result = apiInstance.listWorkspaces();
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling WorkspaceApi#listWorkspaces");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
    }
}

With this code, I need to connect to a production server with a basic-auth (password and username), so how can I add these credentials to this code.

I have tried this but It didn't work, return an exception:

///// java code
   
System.out.println(defaultClient.getAuthentications());
        HttpBasicAuth basicAuthentication = (HttpBasicAuth) defaultClient.getAuthentication("basicAuth");
        basicAuthentication.setUsername("admin");
        basicAuthentication.setPassword("pass");

/// exception msj

{basicAuth=org.openapitools.client.auth.HttpBasicAuth@45c7e403, bearerAuth=org.openapitools.client.auth.HttpBearerAuth@2925bf5b}
Exception when calling WorkspaceApi#listWorkspaces
Status code: 401
Reason: <html>
<head><title>401 Authorization Required</title></head>
<body>
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx</center>
</body>
</html>

Response headers: {content-length=[172], content-type=[text/html], date=[Wed, 27 Apr 2022 19:47:14 GMT], strict-transport-security=[max-age=15724800; includeSubDomains], www-authenticate=[Basic realm="Authentication Required"]}
org.openapitools.client.ApiException: 
    at org.openapitools.client.ApiClient.handleResponse(ApiClient.java:1081)
    at org.openapitools.client.ApiClient.execute(ApiClient.java:994)
    at org.openapitools.client.api.WorkspaceApi.listWorkspacesWithHttpInfo(WorkspaceApi.java:712)
    at org.openapitools.client.api.WorkspaceApi.listWorkspaces(WorkspaceApi.java:694)
    at org.openapitools.client.App.main(App.java:28)

and in the print message, show this:

{basicAuth=org.openapitools.client.auth.HttpBasicAuth@45c7e403, bearerAuth=org.openapitools.client.auth.HttpBearerAuth@2925bf5b}
0 Answers
Related