swagger-api / swagger-codegen

swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
http://swagger.io
Apache License 2.0
16.92k stars 6.03k forks source link

Unable to call a restful service using swagger codegen and saying unauthorized for basic auth #5743

Open ab48917 opened 7 years ago

ab48917 commented 7 years ago

Hi Team,

Consuming a restful service using swagger codegen 2.0 But its failing the authentication.

"swagger": "2.0", "info": { "version": "2.1.0", "title": "GeoES"

Schema does not have securityDefinitions: basic: type: basic description: HTTP Basic Authentication.

So, I tried changing Apiclient authantications map and added manually credentials. But no luck. HttpBasicAuth hba= new HttpBasicAuth();

        hba.setUsername("*******");
        hba.setPassword("*******");
        authentications.put("basic", hba);
   authentications = Collections.unmodifiableMap(authentications);

I changed buildCall to allow but still It's not getting authenticated. Need Help !! String authNames2[] = {"basic"}; updateParamsForAuth(authNames2, queryParams, headerParams);

Thank you

ePaul commented 7 years ago

Sorry, your issue fails to give any details which could be used to help you.

For which language are you generating stuff? (Please post the full command line, or maven plugin configuration, and the Swagger-Codegen version number.) Also, please include or link the API definition file (swagger/OpenAPI), either the full one or a reduced which still allows reproducing your problem. Then, please include the full code which is creating, setting up and using the client.

ab48917 commented 7 years ago

Sorry for inconvenience caused, I generated the stubs for java using below command-

java -jar swagger-codegen-cli-2.2.1.jar generate -i geo.json -l java -o myclient -a "Authorization:Basic ****=="

But my swagger schema does not have securityconfig information. Producer did not write this in json schema file. And still, Producer has used basic authentication. So the problem here , My stubs does not hold any credentials after generating and neither I am manually able to pass the credentials into ApiClient generated class of swagger.

Below is generated ApiClient

/**

package io.swagger.client;

import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.MultipartBuilder; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.Headers; import com.squareup.okhttp.internal.http.HttpMethod; import com.squareup.okhttp.logging.HttpLoggingInterceptor; import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level;

import java.lang.reflect.Type;

import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern;

import java.net.URLEncoder; import java.net.URLConnection;

import java.io.File; import java.io.InputStream; import java.io.IOException; import java.io.UnsupportedEncodingException;

import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate;

import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException;

import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager;

import okio.BufferedSink; import okio.Okio;

import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth;

public class ApiClient { public static final double JAVA_VERSION; public static final boolean IS_ANDROID; public static final int ANDROID_SDK_VERSION;

static {
    JAVA_VERSION =

Double.parseDouble(System.getProperty("java.specification.version")); boolean isAndroid; try { Class.forName("android.app.Activity"); isAndroid = true; } catch (ClassNotFoundException e) { isAndroid = false; } IS_ANDROID = isAndroid; int sdkVersion = 0; if (IS_ANDROID) { try { sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); } catch (Exception e) { try { sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); } catch (Exception e2) { } } } ANDROID_SDK_VERSION = sdkVersion; }

/**
 * The datetime format to be used when

lenientDatetimeFormat is enabled. */ public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

private String basePath = "http://geoestest1.dev.qintra.com";
private boolean lenientOnJson = false;
private boolean debugging = false;
private Map<String, String> defaultHeaderMap = new HashMap<String,

String>(); private String tempFolderPath = null;

private Map<String, Authentication> authentications;

private DateFormat dateFormat;
private DateFormat datetimeFormat;
private boolean lenientDatetimeFormat;
private int dateLength;

private InputStream sslCaCert;
private boolean verifyingSsl;

private OkHttpClient httpClient;
private JSON json;

private HttpLoggingInterceptor loggingInterceptor;

/*
 * Constructor for ApiClient
 */
public ApiClient() {
    httpClient = new OkHttpClient();

    verifyingSsl = true;

    json = new JSON(this);

    /*
     * Use RFC3339 format for date and datetime.
     * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
     */
    this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // Always use UTC as the default time zone when dealing with date

(without time). this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); initDatetimeFormat();

    // Be lenient on datetime formats when parsing datetime from string.
    // See <code>parseDatetime</code>.
    this.lenientDatetimeFormat = true;

    // Set default User-Agent.
    setUserAgent("Swagger-Codegen/1.0.0/java");

    // Setup authentications (key: authentication name, value:

authentication). authentications = new HashMap<String, Authentication>(); HttpBasicAuth hba= new HttpBasicAuth();

        hba.setUsername("EASELSR");
        hba.setPassword("9Em54RUG");
        authentications.put("basic", hba);
    // Prevent the authentications from being modified.
   authentications = Collections.unmodifiableMap(authentications);
}

/**
 * Get base path
 *
 * @return Baes path
 */
public String getBasePath() {
    return basePath;
}

/**
 * Set base path
 *
 * @param basePath Base path of the URL (e.g

http://geoestest1.dev.qintra.com

url.append(escapeString(param.getName())).append("=").append(escapeString(value)); } } }

    return url.toString();
}

/**
 * Set header parameters to the request builder, including default

headers. *

httpClient.setSslSocketFactory(sslContext.getSocketFactory()); } else { httpClient.setSslSocketFactory(null); } httpClient.setHostnameVerifier(hostnameVerifier); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }

private KeyStore newEmptyKeyStore(char[] password) throws

GeneralSecurityException { try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, password); return keyStore; } catch (IOException e) { throw new AssertionError(e); } } }

And, I am calling somewhere like this but it's not carrying the authentication. I tried couple of approaches-

1)ApiClient apiClient = new ApiClient(); hba.setUsername("*"); hba.setPassword("**") AddressesApi customerApi = new AddressesApi(apiClient); ApiResponse<List> customers = customerApi.addressesValidateAddressWithHttpInfo(); Did not work because authentications map is not modifiable.

2)apiClient.addDefaultHeader("Authorization", "Authorization:Basic base64EncodedUser:Pass"); Did not work even I changed buildCall and added this.

String authNames2[] = {"basic"}; updateParamsForAuth(authNames2, queryParams, headerParams);

I am going clueless as how to pass credentials using swagger if producer does not define the securityConfig in swagger schema but still except a credentials to call its operations.

Please assist.

On Wed, May 31, 2017 at 11:00 PM, Paŭlo Ebermann notifications@github.com wrote:

Sorry, your issue fails to give any details which could be used to help you.

For which language are you generating stuff? (Please post the full command line, or maven plugin configuration, and the Swagger-Codegen version number.) Also, please include or link the API definition file (swagger/OpenAPI), either the full one or a reduced which still allows reproducing your problem. Then, please include the full code which is creating, setting up and using the client.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/swagger-api/swagger-codegen/issues/5743#issuecomment-305259517, or mute the thread https://github.com/notifications/unsubscribe-auth/AaFtbITkM2eWcLhOUNnyKVUqWEosjZQAks5r_aOtgaJpZM4Nrpgw .

M4GiK commented 4 years ago

I have the same problem like above. Genereated code for java, using: java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -i https://developer.allegro.pl/swagger.yaml -g java -o samples/client/allegro -p pl.com.kams