[csharp-netcore] Update RestSharp and add client_credentials auth support (#12789)

* Update RestSharp to v108

* Add OAuth2 Application (client_credentials) authentication

* Run generators and fix typos

* Undo accidental python and rust changes

* Add documentation, fix authenticator bug, and fix user agent bug

* Fix tests

Missed some changes in the mustache templates.
Also had to update the `netcoreapp2.0` test project to `netcoreapp3.1` for compatibility with RestSharp

* Switch HttpUtility to WebUtility for compatibility
This commit is contained in:
Jared Bates 2022-07-20 06:25:29 -05:00 committed by GitHub
parent 6d44f97d6c
commit 2dcc319e13
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
123 changed files with 3601 additions and 1152 deletions

View File

@ -307,7 +307,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|BearerToken|✗|OAS3
|OAuth2_Implicit|✓|OAS2,OAS3
|OAuth2_Password|✗|OAS2,OAS3
|OAuth2_ClientCredentials||OAS2,OAS3
|OAuth2_ClientCredentials||OAS2,OAS3
|OAuth2_AuthorizationCode|✗|OAS2,OAS3
### Wire Format Feature

View File

@ -84,6 +84,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
protected final Map<String, String> frameworks;
protected String packageGuid = "{" + java.util.UUID.randomUUID().toString().toUpperCase(Locale.ROOT) + "}";
protected String clientPackage = "Org.OpenAPITools.Client";
protected String authFolder = "Auth";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
@ -119,6 +120,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
.includeDocumentationFeatures(DocumentationFeature.Readme)
.securityFeatures(EnumSet.of(
SecurityFeature.OAuth2_Implicit,
SecurityFeature.OAuth2_ClientCredentials,
SecurityFeature.BasicAuth,
SecurityFeature.ApiKey
))
@ -759,6 +761,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
String packageFolder = sourceFolder + File.separator + packageName;
String clientPackageDir = packageFolder + File.separator + clientPackage;
String modelPackageDir = packageFolder + File.separator + modelPackage;
String authPackageDir = clientPackageDir + File.separator + authFolder;
String testPackageFolder = testFolder + File.separator + testPackageName;
additionalProperties.put("testPackageName", testPackageName);
@ -782,7 +785,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
if (HTTPCLIENT.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("FileParameter.mustache", clientPackageDir, "FileParameter.cs"));
typeMapping.put("file", "FileParameter");
addRestSharpSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir);
addRestSharpSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir, authPackageDir);
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
} else if (GENERICHOST.equals(getLibrary())) {
@ -790,7 +793,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
additionalProperties.put("apiDocPath", apiDocPath + File.separatorChar + "apis");
additionalProperties.put("modelDocPath", modelDocPath + File.separatorChar + "models");
} else {
addRestSharpSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir);
addRestSharpSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir, authPackageDir);
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
}
@ -849,7 +852,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
}
public void addRestSharpSupportingFiles(final String clientPackageDir, final String packageFolder,
final AtomicReference<Boolean> excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir) {
final AtomicReference<Boolean> excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir, final String authPackageDir) {
supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, "IApiAccessor.cs"));
supportingFiles.add(new SupportingFile("Configuration.mustache", clientPackageDir, "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", clientPackageDir, "ApiClient.cs"));
@ -896,6 +899,12 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("appveyor.mustache", "", "appveyor.yml"));
supportingFiles.add(new SupportingFile("AbstractOpenAPISchema.mustache", modelPackageDir, "AbstractOpenAPISchema.cs"));
if (ProcessUtils.hasOAuthMethods(openAPI)) {
supportingFiles.add(new SupportingFile("auth/OAuthAuthenticator.mustache", authPackageDir, "OAuthAuthenticator.cs"));
supportingFiles.add(new SupportingFile("auth/TokenResponse.mustache", authPackageDir, "TokenResponse.cs"));
supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authPackageDir, "OAuthFlow.cs"));
}
}
public void addGenericHostSupportingFiles(final String clientPackageDir, final String packageFolder,

View File

@ -19,20 +19,22 @@ using System.Web;
{{/netStandard}}
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp;
using RestSharp.Deserializers;
using RestSharp.Serializers;
using RestSharpMethod = RestSharp.Method;
{{#supportsRetry}}
using Polly;
{{/supportsRetry}}
{{#hasOAuthMethods}}
using {{packageName}}.Client.Auth;
{{/hasOAuthMethods}}
namespace {{packageName}}.Client
{
/// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer
internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer
{
private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json";
@ -78,7 +80,9 @@ namespace {{packageName}}.Client
}
}
public T Deserialize<T>(IRestResponse response)
public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);
public T Deserialize<T>(RestResponse response)
{
var result = (T)Deserialize(response, typeof(T));
return result;
@ -90,7 +94,7 @@ namespace {{packageName}}.Client
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
internal object Deserialize(IRestResponse response, Type type)
internal object Deserialize(RestResponse response, Type type)
{
if (type == typeof(byte[])) // return byte array
{
@ -143,15 +147,22 @@ namespace {{packageName}}.Client
}
}
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public ISerializer Serializer => this;
public IDeserializer Deserializer => this;
public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept;
public SupportsContentType SupportsContentType => contentType =>
contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) ||
contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase);
public string ContentType
{
get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); }
}
public DataFormat DataFormat => DataFormat.Json;
}
{{! NOTE: Any changes related to RestSharp should be done in this class. All other client classes are for extensibility by consumers.}}
/// <summary>
@ -183,14 +194,14 @@ namespace {{packageName}}.Client
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request);
partial void InterceptRequest(RestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
partial void InterceptResponse(RestRequest request, RestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url.
@ -225,25 +236,25 @@ namespace {{packageName}}.Client
switch (method)
{
case HttpMethod.Get:
other = RestSharpMethod.GET;
other = RestSharpMethod.Get;
break;
case HttpMethod.Post:
other = RestSharpMethod.POST;
other = RestSharpMethod.Post;
break;
case HttpMethod.Put:
other = RestSharpMethod.PUT;
other = RestSharpMethod.Put;
break;
case HttpMethod.Delete:
other = RestSharpMethod.DELETE;
other = RestSharpMethod.Delete;
break;
case HttpMethod.Head:
other = RestSharpMethod.HEAD;
other = RestSharpMethod.Head;
break;
case HttpMethod.Options:
other = RestSharpMethod.OPTIONS;
other = RestSharpMethod.Options;
break;
case HttpMethod.Patch:
other = RestSharpMethod.PATCH;
other = RestSharpMethod.Patch;
break;
default:
throw new ArgumentOutOfRangeException("method", method, null);
@ -274,11 +285,7 @@ namespace {{packageName}}.Client
if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method))
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
RestRequest request = new RestRequest(path, Method(method));
if (options.PathParameters != null)
{
@ -373,25 +380,17 @@ namespace {{packageName}}.Client
var bytes = ClientUtils.ReadAsBytes(file);
var fileStream = file as FileStream;
if (fileStream != null)
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)));
request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name));
else
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided"));
request.AddFile(fileParam.Key, bytes, "no_file_name_provided");
}
}
}
if (options.Cookies != null && options.Cookies.Count > 0)
{
foreach (var cookie in options.Cookies)
{
request.AddCookie(cookie.Name, cookie.Value);
}
}
return request;
}
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response)
private ApiResponse<T> ToApiResponse<T>(RestResponse<T> response)
{
T result = response.Data;
string rawContent = response.Content;
@ -410,9 +409,17 @@ namespace {{packageName}}.Client
}
}
if (response.ContentHeaders != null)
{
foreach (var responseHeader in response.ContentHeaders)
{
transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value));
}
}
if (response.Cookies != null)
{
foreach (var responseCookies in response.Cookies)
foreach (var responseCookies in response.Cookies.Cast<Cookie>())
{
transformed.Cookies.Add(
new Cookie(
@ -430,54 +437,48 @@ namespace {{packageName}}.Client
private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration)
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
var cookies = new CookieContainer();
if (options.Cookies != null && options.Cookies.Count > 0)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
foreach (var cookie in options.Cookies)
{
cookies.Add(new Cookie(cookie.Name, cookie.Value));
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
var clientOptions = new RestClientOptions(baseUrl)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
ClientCertificates = configuration.ClientCertificates,
CookieContainer = cookies,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
RestClient client = new RestClient(clientOptions)
.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
{{#hasOAuthMethods}}
if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(configuration.OAuthClientId) &&
!string.IsNullOrEmpty(configuration.OAuthClientSecret) &&
configuration.OAuthFlow != null)
{
client = client.UseAuthenticator(new OAuthAuthenticator(
configuration.OAuthTokenUrl,
configuration.OAuthClientId,
configuration.OAuthClientSecret,
configuration.OAuthFlow,
SerializerSettings,
configuration));
}
{{/hasOAuthMethods}}
InterceptRequest(req);
IRestResponse<T> response;
RestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null)
{
var policy = RetryConfiguration.RetryPolicy;
@ -525,7 +526,7 @@ namespace {{packageName}}.Client
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,
@ -555,54 +556,37 @@ namespace {{packageName}}.Client
private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
var clientOptions = new RestClientOptions(baseUrl)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
}
else
ClientCertificates = configuration.ClientCertificates,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
RestClient client = new RestClient(clientOptions)
.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
{{#hasOAuthMethods}}
if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(configuration.OAuthClientId) &&
!string.IsNullOrEmpty(configuration.OAuthClientSecret) &&
configuration.OAuthFlow != null)
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
client = client.UseAuthenticator(new OAuthAuthenticator(
configuration.OAuthTokenUrl,
configuration.OAuthClientId,
configuration.OAuthClientSecret,
configuration.OAuthFlow,
SerializerSettings,
configuration));
}
{{/hasOAuthMethods}}
InterceptRequest(req);
IRestResponse<T> response;
RestResponse<T> response;
{{#supportsRetry}}
if (RetryConfiguration.AsyncRetryPolicy != null)
{
@ -647,7 +631,7 @@ namespace {{packageName}}.Client
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,

View File

@ -11,6 +11,9 @@ using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Net.Http;
{{#hasOAuthMethods}}using {{packageName}}.Client.Auth;
{{/hasOAuthMethods}}
namespace {{packageName}}.Client
{
@ -118,7 +121,7 @@ namespace {{packageName}}.Client
public Configuration()
{
Proxy = null;
UserAgent = "{{httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{packageVersion}}/csharp{{/httpUserAgent}}";
UserAgent = WebUtility.UrlEncode("{{httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{packageVersion}}/csharp{{/httpUserAgent}}");
BasePath = "{{{basePath}}}";
DefaultHeaders = new {{^net35}}Concurrent{{/net35}}Dictionary<string, string>();
ApiKey = new {{^net35}}Concurrent{{/net35}}Dictionary<string, string>();
@ -328,6 +331,32 @@ namespace {{packageName}}.Client
/// <value>The access token.</value>
public virtual string AccessToken { get; set; }
{{#hasOAuthMethods}}
/// <summary>
/// Gets or sets the token URL for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Token URL.</value>
public virtual string OAuthTokenUrl { get; set; }
/// <summary>
/// Gets or sets the client ID for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Client ID.</value>
public virtual string OAuthClientId { get; set; }
/// <summary>
/// Gets or sets the client secret for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Client Secret.</value>
public virtual string OAuthClientSecret { get; set; }
/// <summary>
/// Gets or sets the flow for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Flow.</value>
public virtual OAuthFlow? OAuthFlow { get; set; }
{{/hasOAuthMethods}}
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
@ -655,6 +684,12 @@ namespace {{packageName}}.Client
Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken,
{{#hasOAuthMethods}}
OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl,
OAuthClientId = second.OAuthClientId ?? first.OAuthClientId,
OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret,
OAuthFlow = second.OAuthFlow ?? first.OAuthFlow,
{{/hasOAuthMethods}}
{{#hasHttpSignatureMethods}}
HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration,
{{/hasHttpSignatureMethods}}

View File

@ -4,6 +4,8 @@ using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography.X509Certificates;
{{#hasOAuthMethods}}using {{packageName}}.Client.Auth;
{{/hasOAuthMethods}}
namespace {{packageName}}.Client
{
@ -18,6 +20,32 @@ namespace {{packageName}}.Client
/// <value>Access token.</value>
string AccessToken { get; }
{{#hasOAuthMethods}}
/// <summary>
/// Gets the OAuth token URL.
/// </summary>
/// <value>OAuth Token URL.</value>
string OAuthTokenUrl { get; }
/// <summary>
/// Gets the OAuth client ID.
/// </summary>
/// <value>OAuth Client ID.</value>
string OAuthClientId { get; }
/// <summary>
/// Gets the OAuth client secret.
/// </summary>
/// <value>OAuth Client Secret.</value>
string OAuthClientSecret { get; }
/// <summary>
/// Gets the OAuth flow.
/// </summary>
/// <value>OAuth Flow.</value>
OAuthFlow? OAuthFlow { get; }
{{/hasOAuthMethods}}
/// <summary>
/// Gets the API key.
/// </summary>

View File

@ -60,6 +60,13 @@ namespace {{packageName}}.Client
/// </summary>
public Object Data { get; set; }
{{#hasOAuthMethods}}
/// <summary>
/// If request should be authenticated with OAuth.
/// </summary>
public bool OAuth { get; set; }
{{/hasOAuthMethods}}
/// <summary>
/// Constructs a new instance of <see cref="RequestOptions"/>
/// </summary>

View File

@ -19,12 +19,12 @@ namespace {{packageName}}.Client
/// <summary>
/// Retry policy
/// </summary>
public static Policy<IRestResponse> RetryPolicy { get; set; }
public static Policy<RestResponse> RetryPolicy { get; set; }
/// <summary>
/// Async retry policy
/// </summary>
public static AsyncPolicy<IRestResponse> AsyncRetryPolicy { get; set; }
public static AsyncPolicy<RestResponse> AsyncRetryPolicy { get; set; }
{{/useRestSharp}}
{{#useHttpClient}}
/// <summary>

View File

@ -7,6 +7,8 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using {{packageName}}.Client;
{{#hasOAuthMethods}}using {{packageName}}.Client.Auth;
{{/hasOAuthMethods}}
{{#hasImport}}using {{packageName}}.{{modelPackage}};
{{/hasImport}}
@ -438,10 +440,22 @@ namespace {{packageName}}.{{apiPackage}}
{{/isBasicBearer}}
{{#isOAuth}}
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
{{#hasOAuthMethods}}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
{{/hasOAuthMethods}}
}
{{/isOAuth}}
{{#isHttpSignature}}
if (this.Configuration.HttpSigningConfiguration != null)
@ -669,10 +683,22 @@ namespace {{packageName}}.{{apiPackage}}
{{/isBasic}}
{{#isOAuth}}
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
{{#hasOAuthMethods}}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
{{/hasOAuthMethods}}
}
{{/isOAuth}}
{{#isHttpSignature}}
if (this.Configuration.HttpSigningConfiguration != null)

View File

@ -0,0 +1,87 @@
{{>partial_header}}
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Authenticators;
namespace {{packageName}}.Client.Auth
{
/// <summary>
/// An authenticator for OAuth2 authentication flows
/// </summary>
public class OAuthAuthenticator : AuthenticatorBase
{
readonly string _tokenUrl;
readonly string _clientId;
readonly string _clientSecret;
readonly string _grantType;
readonly JsonSerializerSettings _serializerSettings;
readonly IReadableConfiguration _configuration;
/// <summary>
/// Initialize the OAuth2 Authenticator
/// </summary>
public OAuthAuthenticator(
string tokenUrl,
string clientId,
string clientSecret,
OAuthFlow? flow,
JsonSerializerSettings serializerSettings,
IReadableConfiguration configuration) : base("")
{
_tokenUrl = tokenUrl;
_clientId = clientId;
_clientSecret = clientSecret;
_serializerSettings = serializerSettings;
_configuration = configuration;
switch (flow)
{
/*case OAuthFlow.ACCESS_CODE:
_grantType = "authorization_code";
break;
case OAuthFlow.IMPLICIT:
_grantType = "implicit";
break;
case OAuthFlow.PASSWORD:
_grantType = "password";
break;*/
case OAuthFlow.APPLICATION:
_grantType = "client_credentials";
break;
default:
break;
}
}
/// <summary>
/// Creates an authentication parameter from an access token.
/// </summary>
/// <param name="accessToken">Access token to create a parameter from.</param>
/// <returns>An authentication parameter.</returns>
protected override async ValueTask<Parameter> GetAuthenticationParameter(string accessToken)
{
var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token;
return new HeaderParameter(KnownHeaders.Authorization, token);
}
/// <summary>
/// Gets the token from the OAuth2 server.
/// </summary>
/// <returns>An authentication token.</returns>
async Task<string> GetToken()
{
var client = new RestClient(_tokenUrl)
.UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration));
var request = new RestRequest()
.AddParameter("grant_type", _grantType)
.AddParameter("client_id", _clientId)
.AddParameter("client_secret", _clientSecret);
var response = await client.PostAsync<TokenResponse>(request);
return $"{response.TokenType} {response.AccessToken}";
}
}
}

View File

@ -0,0 +1,19 @@
{{>partial_header}}
namespace {{packageName}}.Client.Auth
{
/// <summary>
/// Available flows for OAuth2 authentication
/// </summary>
public enum OAuthFlow
{
/// <summary>Authorization code flow</summary>
ACCESS_CODE,
/// <summary>Implicit flow</summary>
IMPLICIT,
/// <summary>Password flow</summary>
PASSWORD,
/// <summary>Client credentials flow</summary>
APPLICATION
}
}

View File

@ -0,0 +1,14 @@
{{>partial_header}}
using Newtonsoft.Json;
namespace {{packageName}}.Client.Auth
{
class TokenResponse
{
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("access_token")]
public string AccessToken { get; set; }
}
}

View File

@ -28,11 +28,11 @@
<PackageReference Include="CompareNETObjects" Version="4.61.0" />
{{/useCompareNetObjects}}
{{^useGenericHost}}
<PackageReference Include="JsonSubTypes" Version="1.8.0" />
<PackageReference Include="JsonSubTypes" Version="1.9.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
{{/useGenericHost}}
{{#useRestSharp}}
<PackageReference Include="RestSharp" Version="106.13.0" />
<PackageReference Include="RestSharp" Version="108.0.1" />
{{/useRestSharp}}
{{#useGenericHost}}
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />

View File

@ -32,12 +32,12 @@
<dependency id="Newtonsoft.Json" version="13.0.1" />
{{#useRestSharp}}
<dependency id="RestSharp" version="106.13.0" />
<dependency id="RestSharp" version="108.0.1" />
{{/useRestSharp}}
{{#useCompareNetObjects}}
<dependency id="CompareNETObjects" version="4.61.0" />
{{/useCompareNetObjects}}
<dependency id="JsonSubTypes" version="1.8.0" />
<dependency id="JsonSubTypes" version="1.9.0" />
{{#validatable}}
<dependency id="System.ComponentModel.Annotations" version="5.0.0" />
{{/validatable}}

View File

@ -24,9 +24,8 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp;
using RestSharp.Deserializers;
using RestSharp.Serializers;
using RestSharpMethod = RestSharp.Method;
using Polly;
@ -35,7 +34,7 @@ namespace Org.OpenAPITools.Client
/// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer
internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer
{
private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json";
@ -81,7 +80,9 @@ namespace Org.OpenAPITools.Client
}
}
public T Deserialize<T>(IRestResponse response)
public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);
public T Deserialize<T>(RestResponse response)
{
var result = (T)Deserialize(response, typeof(T));
return result;
@ -93,7 +94,7 @@ namespace Org.OpenAPITools.Client
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
internal object Deserialize(IRestResponse response, Type type)
internal object Deserialize(RestResponse response, Type type)
{
if (type == typeof(byte[])) // return byte array
{
@ -146,15 +147,22 @@ namespace Org.OpenAPITools.Client
}
}
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public ISerializer Serializer => this;
public IDeserializer Deserializer => this;
public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept;
public SupportsContentType SupportsContentType => contentType =>
contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) ||
contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase);
public string ContentType
{
get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); }
}
public DataFormat DataFormat => DataFormat.Json;
}
/// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementations),
@ -185,14 +193,14 @@ namespace Org.OpenAPITools.Client
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request);
partial void InterceptRequest(RestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
partial void InterceptResponse(RestRequest request, RestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url.
@ -227,25 +235,25 @@ namespace Org.OpenAPITools.Client
switch (method)
{
case HttpMethod.Get:
other = RestSharpMethod.GET;
other = RestSharpMethod.Get;
break;
case HttpMethod.Post:
other = RestSharpMethod.POST;
other = RestSharpMethod.Post;
break;
case HttpMethod.Put:
other = RestSharpMethod.PUT;
other = RestSharpMethod.Put;
break;
case HttpMethod.Delete:
other = RestSharpMethod.DELETE;
other = RestSharpMethod.Delete;
break;
case HttpMethod.Head:
other = RestSharpMethod.HEAD;
other = RestSharpMethod.Head;
break;
case HttpMethod.Options:
other = RestSharpMethod.OPTIONS;
other = RestSharpMethod.Options;
break;
case HttpMethod.Patch:
other = RestSharpMethod.PATCH;
other = RestSharpMethod.Patch;
break;
default:
throw new ArgumentOutOfRangeException("method", method, null);
@ -276,11 +284,7 @@ namespace Org.OpenAPITools.Client
if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method))
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
RestRequest request = new RestRequest(path, Method(method));
if (options.PathParameters != null)
{
@ -375,25 +379,17 @@ namespace Org.OpenAPITools.Client
var bytes = ClientUtils.ReadAsBytes(file);
var fileStream = file as FileStream;
if (fileStream != null)
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)));
request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name));
else
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided"));
request.AddFile(fileParam.Key, bytes, "no_file_name_provided");
}
}
}
if (options.Cookies != null && options.Cookies.Count > 0)
{
foreach (var cookie in options.Cookies)
{
request.AddCookie(cookie.Name, cookie.Value);
}
}
return request;
}
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response)
private ApiResponse<T> ToApiResponse<T>(RestResponse<T> response)
{
T result = response.Data;
string rawContent = response.Content;
@ -412,9 +408,17 @@ namespace Org.OpenAPITools.Client
}
}
if (response.ContentHeaders != null)
{
foreach (var responseHeader in response.ContentHeaders)
{
transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value));
}
}
if (response.Cookies != null)
{
foreach (var responseCookies in response.Cookies)
foreach (var responseCookies in response.Cookies.Cast<Cookie>())
{
transformed.Cookies.Add(
new Cookie(
@ -432,54 +436,32 @@ namespace Org.OpenAPITools.Client
private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration)
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
var cookies = new CookieContainer();
if (options.Cookies != null && options.Cookies.Count > 0)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
foreach (var cookie in options.Cookies)
{
cookies.Add(new Cookie(cookie.Name, cookie.Value));
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
var clientOptions = new RestClientOptions(baseUrl)
{
client.Proxy = configuration.Proxy;
}
ClientCertificates = configuration.ClientCertificates,
CookieContainer = cookies,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
}
RestClient client = new RestClient(clientOptions)
.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
InterceptRequest(req);
IRestResponse<T> response;
RestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null)
{
var policy = RetryConfiguration.RetryPolicy;
@ -527,7 +509,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,
@ -556,54 +538,21 @@ namespace Org.OpenAPITools.Client
private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
var clientOptions = new RestClientOptions(baseUrl)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
ClientCertificates = configuration.ClientCertificates,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
}
RestClient client = new RestClient(clientOptions)
.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
InterceptRequest(req);
IRestResponse<T> response;
RestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
@ -644,7 +593,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,

View File

@ -17,6 +17,7 @@ using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Net.Http;
namespace Org.OpenAPITools.Client
{
@ -108,7 +109,7 @@ namespace Org.OpenAPITools.Client
public Configuration()
{
Proxy = null;
UserAgent = "OpenAPI-Generator/1.0.0/csharp";
UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp");
BasePath = "http://localhost";
DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>();

View File

@ -21,11 +21,11 @@ namespace Org.OpenAPITools.Client
/// <summary>
/// Retry policy
/// </summary>
public static Policy<IRestResponse> RetryPolicy { get; set; }
public static Policy<RestResponse> RetryPolicy { get; set; }
/// <summary>
/// Async retry policy
/// </summary>
public static AsyncPolicy<IRestResponse> AsyncRetryPolicy { get; set; }
public static AsyncPolicy<RestResponse> AsyncRetryPolicy { get; set; }
}
}

View File

@ -21,9 +21,9 @@
<ItemGroup>
<PackageReference Include="CompareNETObjects" Version="4.61.0" />
<PackageReference Include="JsonSubTypes" Version="1.8.0" />
<PackageReference Include="JsonSubTypes" Version="1.9.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="RestSharp" Version="106.13.0" />
<PackageReference Include="RestSharp" Version="108.0.1" />
<PackageReference Include="Polly" Version="7.2.3" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup>

View File

@ -98,6 +98,9 @@ src/Org.OpenAPITools/Api/UserApi.cs
src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.cs
src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs
src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs
src/Org.OpenAPITools/Client/Auth/TokenResponse.cs
src/Org.OpenAPITools/Client/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api
@ -674,10 +675,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<Object>("/pet", localVarRequestOptions, this.Configuration);
@ -769,10 +780,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<Object>("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -844,10 +865,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Delete<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration);
@ -921,10 +952,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.DeleteAsync<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1015,10 +1056,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Get<List<Pet>>("/pet/findByStatus", localVarRequestOptions, this.Configuration);
@ -1111,10 +1162,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<List<Pet>>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1207,10 +1268,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Get<List<Pet>>("/pet/findByTags", localVarRequestOptions, this.Configuration);
@ -1305,10 +1376,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<List<Pet>>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1542,10 +1623,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Put<Object>("/pet", localVarRequestOptions, this.Configuration);
@ -1637,10 +1728,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PutAsync<Object>("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1719,10 +1820,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration);
@ -1803,10 +1914,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1887,10 +2008,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<ApiResponse>("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration);
@ -1973,10 +2104,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<ApiResponse>("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -2061,10 +2202,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<ApiResponse>("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration);
@ -2151,10 +2302,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<ApiResponse>("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -24,18 +24,18 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp;
using RestSharp.Deserializers;
using RestSharp.Serializers;
using RestSharpMethod = RestSharp.Method;
using Polly;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer
internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer
{
private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json";
@ -81,7 +81,9 @@ namespace Org.OpenAPITools.Client
}
}
public T Deserialize<T>(IRestResponse response)
public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);
public T Deserialize<T>(RestResponse response)
{
var result = (T)Deserialize(response, typeof(T));
return result;
@ -93,7 +95,7 @@ namespace Org.OpenAPITools.Client
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
internal object Deserialize(IRestResponse response, Type type)
internal object Deserialize(RestResponse response, Type type)
{
if (type == typeof(byte[])) // return byte array
{
@ -146,15 +148,22 @@ namespace Org.OpenAPITools.Client
}
}
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public ISerializer Serializer => this;
public IDeserializer Deserializer => this;
public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept;
public SupportsContentType SupportsContentType => contentType =>
contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) ||
contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase);
public string ContentType
{
get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); }
}
public DataFormat DataFormat => DataFormat.Json;
}
/// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementations),
@ -185,14 +194,14 @@ namespace Org.OpenAPITools.Client
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request);
partial void InterceptRequest(RestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
partial void InterceptResponse(RestRequest request, RestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url.
@ -227,25 +236,25 @@ namespace Org.OpenAPITools.Client
switch (method)
{
case HttpMethod.Get:
other = RestSharpMethod.GET;
other = RestSharpMethod.Get;
break;
case HttpMethod.Post:
other = RestSharpMethod.POST;
other = RestSharpMethod.Post;
break;
case HttpMethod.Put:
other = RestSharpMethod.PUT;
other = RestSharpMethod.Put;
break;
case HttpMethod.Delete:
other = RestSharpMethod.DELETE;
other = RestSharpMethod.Delete;
break;
case HttpMethod.Head:
other = RestSharpMethod.HEAD;
other = RestSharpMethod.Head;
break;
case HttpMethod.Options:
other = RestSharpMethod.OPTIONS;
other = RestSharpMethod.Options;
break;
case HttpMethod.Patch:
other = RestSharpMethod.PATCH;
other = RestSharpMethod.Patch;
break;
default:
throw new ArgumentOutOfRangeException("method", method, null);
@ -276,11 +285,7 @@ namespace Org.OpenAPITools.Client
if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method))
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
RestRequest request = new RestRequest(path, Method(method));
if (options.PathParameters != null)
{
@ -375,25 +380,17 @@ namespace Org.OpenAPITools.Client
var bytes = ClientUtils.ReadAsBytes(file);
var fileStream = file as FileStream;
if (fileStream != null)
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)));
request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name));
else
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided"));
request.AddFile(fileParam.Key, bytes, "no_file_name_provided");
}
}
}
if (options.Cookies != null && options.Cookies.Count > 0)
{
foreach (var cookie in options.Cookies)
{
request.AddCookie(cookie.Name, cookie.Value);
}
}
return request;
}
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response)
private ApiResponse<T> ToApiResponse<T>(RestResponse<T> response)
{
T result = response.Data;
string rawContent = response.Content;
@ -412,9 +409,17 @@ namespace Org.OpenAPITools.Client
}
}
if (response.ContentHeaders != null)
{
foreach (var responseHeader in response.ContentHeaders)
{
transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value));
}
}
if (response.Cookies != null)
{
foreach (var responseCookies in response.Cookies)
foreach (var responseCookies in response.Cookies.Cast<Cookie>())
{
transformed.Cookies.Add(
new Cookie(
@ -432,54 +437,46 @@ namespace Org.OpenAPITools.Client
private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration)
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
var cookies = new CookieContainer();
if (options.Cookies != null && options.Cookies.Count > 0)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
foreach (var cookie in options.Cookies)
{
cookies.Add(new Cookie(cookie.Name, cookie.Value));
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
var clientOptions = new RestClientOptions(baseUrl)
{
client.Proxy = configuration.Proxy;
}
ClientCertificates = configuration.ClientCertificates,
CookieContainer = cookies,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
RestClient client = new RestClient(clientOptions)
.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
if (configuration.ClientCertificates != null)
if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(configuration.OAuthClientId) &&
!string.IsNullOrEmpty(configuration.OAuthClientSecret) &&
configuration.OAuthFlow != null)
{
client.ClientCertificates = configuration.ClientCertificates;
client = client.UseAuthenticator(new OAuthAuthenticator(
configuration.OAuthTokenUrl,
configuration.OAuthClientId,
configuration.OAuthClientSecret,
configuration.OAuthFlow,
SerializerSettings,
configuration));
}
InterceptRequest(req);
IRestResponse<T> response;
RestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null)
{
var policy = RetryConfiguration.RetryPolicy;
@ -527,7 +524,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,
@ -556,54 +553,35 @@ namespace Org.OpenAPITools.Client
private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
var clientOptions = new RestClientOptions(baseUrl)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
}
else
ClientCertificates = configuration.ClientCertificates,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
RestClient client = new RestClient(clientOptions)
.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(configuration.OAuthClientId) &&
!string.IsNullOrEmpty(configuration.OAuthClientSecret) &&
configuration.OAuthFlow != null)
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
client = client.UseAuthenticator(new OAuthAuthenticator(
configuration.OAuthTokenUrl,
configuration.OAuthClientId,
configuration.OAuthClientSecret,
configuration.OAuthFlow,
SerializerSettings,
configuration));
}
InterceptRequest(req);
IRestResponse<T> response;
RestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
@ -644,7 +622,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,

View File

@ -0,0 +1,95 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Authenticators;
namespace Org.OpenAPITools.Client.Auth
{
/// <summary>
/// An authenticator for OAuth2 authentication flows
/// </summary>
public class OAuthAuthenticator : AuthenticatorBase
{
readonly string _tokenUrl;
readonly string _clientId;
readonly string _clientSecret;
readonly string _grantType;
readonly JsonSerializerSettings _serializerSettings;
readonly IReadableConfiguration _configuration;
/// <summary>
/// Initialize the OAuth2 Authenticator
/// </summary>
public OAuthAuthenticator(
string tokenUrl,
string clientId,
string clientSecret,
OAuthFlow? flow,
JsonSerializerSettings serializerSettings,
IReadableConfiguration configuration) : base("")
{
_tokenUrl = tokenUrl;
_clientId = clientId;
_clientSecret = clientSecret;
_serializerSettings = serializerSettings;
_configuration = configuration;
switch (flow)
{
/*case OAuthFlow.ACCESS_CODE:
_grantType = "authorization_code";
break;
case OAuthFlow.IMPLICIT:
_grantType = "implicit";
break;
case OAuthFlow.PASSWORD:
_grantType = "password";
break;*/
case OAuthFlow.APPLICATION:
_grantType = "client_credentials";
break;
default:
break;
}
}
/// <summary>
/// Creates an authentication parameter from an access token.
/// </summary>
/// <param name="accessToken">Access token to create a parameter from.</param>
/// <returns>An authentication parameter.</returns>
protected override async ValueTask<Parameter> GetAuthenticationParameter(string accessToken)
{
var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token;
return new HeaderParameter(KnownHeaders.Authorization, token);
}
/// <summary>
/// Gets the token from the OAuth2 server.
/// </summary>
/// <returns>An authentication token.</returns>
async Task<string> GetToken()
{
var client = new RestClient(_tokenUrl)
.UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration));
var request = new RestRequest()
.AddParameter("grant_type", _grantType)
.AddParameter("client_id", _clientId)
.AddParameter("client_secret", _clientSecret);
var response = await client.PostAsync<TokenResponse>(request);
return $"{response.TokenType} {response.AccessToken}";
}
}
}

View File

@ -0,0 +1,27 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
namespace Org.OpenAPITools.Client.Auth
{
/// <summary>
/// Available flows for OAuth2 authentication
/// </summary>
public enum OAuthFlow
{
/// <summary>Authorization code flow</summary>
ACCESS_CODE,
/// <summary>Implicit flow</summary>
IMPLICIT,
/// <summary>Password flow</summary>
PASSWORD,
/// <summary>Client credentials flow</summary>
APPLICATION
}
}

View File

@ -0,0 +1,22 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Newtonsoft.Json;
namespace Org.OpenAPITools.Client.Auth
{
class TokenResponse
{
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("access_token")]
public string AccessToken { get; set; }
}
}

View File

@ -17,6 +17,8 @@ using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Net.Http;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
@ -113,7 +115,7 @@ namespace Org.OpenAPITools.Client
public Configuration()
{
Proxy = null;
UserAgent = "OpenAPI-Generator/1.0.0/csharp";
UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp");
BasePath = "http://petstore.swagger.io:80/v2";
DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>();
@ -361,6 +363,30 @@ namespace Org.OpenAPITools.Client
/// <value>The access token.</value>
public virtual string AccessToken { get; set; }
/// <summary>
/// Gets or sets the token URL for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Token URL.</value>
public virtual string OAuthTokenUrl { get; set; }
/// <summary>
/// Gets or sets the client ID for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Client ID.</value>
public virtual string OAuthClientId { get; set; }
/// <summary>
/// Gets or sets the client secret for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Client Secret.</value>
public virtual string OAuthClientSecret { get; set; }
/// <summary>
/// Gets or sets the flow for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Flow.</value>
public virtual OAuthFlow? OAuthFlow { get; set; }
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
@ -684,6 +710,10 @@ namespace Org.OpenAPITools.Client
Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken,
OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl,
OAuthClientId = second.OAuthClientId ?? first.OAuthClientId,
OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret,
OAuthFlow = second.OAuthFlow ?? first.OAuthFlow,
HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat,

View File

@ -12,6 +12,7 @@ using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client
/// <value>Access token.</value>
string AccessToken { get; }
/// <summary>
/// Gets the OAuth token URL.
/// </summary>
/// <value>OAuth Token URL.</value>
string OAuthTokenUrl { get; }
/// <summary>
/// Gets the OAuth client ID.
/// </summary>
/// <value>OAuth Client ID.</value>
string OAuthClientId { get; }
/// <summary>
/// Gets the OAuth client secret.
/// </summary>
/// <value>OAuth Client Secret.</value>
string OAuthClientSecret { get; }
/// <summary>
/// Gets the OAuth flow.
/// </summary>
/// <value>OAuth Flow.</value>
OAuthFlow? OAuthFlow { get; }
/// <summary>
/// Gets the API key.
/// </summary>

View File

@ -68,6 +68,11 @@ namespace Org.OpenAPITools.Client
/// </summary>
public Object Data { get; set; }
/// <summary>
/// If request should be authenticated with OAuth.
/// </summary>
public bool OAuth { get; set; }
/// <summary>
/// Constructs a new instance of <see cref="RequestOptions"/>
/// </summary>

View File

@ -21,11 +21,11 @@ namespace Org.OpenAPITools.Client
/// <summary>
/// Retry policy
/// </summary>
public static Policy<IRestResponse> RetryPolicy { get; set; }
public static Policy<RestResponse> RetryPolicy { get; set; }
/// <summary>
/// Async retry policy
/// </summary>
public static AsyncPolicy<IRestResponse> AsyncRetryPolicy { get; set; }
public static AsyncPolicy<RestResponse> AsyncRetryPolicy { get; set; }
}
}

View File

@ -21,9 +21,9 @@
<ItemGroup>
<PackageReference Include="CompareNETObjects" Version="4.61.0" />
<PackageReference Include="JsonSubTypes" Version="1.8.0" />
<PackageReference Include="JsonSubTypes" Version="1.9.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="RestSharp" Version="106.13.0" />
<PackageReference Include="RestSharp" Version="108.0.1" />
<PackageReference Include="Polly" Version="7.2.3" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup>

View File

@ -97,6 +97,9 @@ src/Org.OpenAPITools/Api/UserApi.cs
src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.cs
src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs
src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs
src/Org.OpenAPITools/Client/Auth/TokenResponse.cs
src/Org.OpenAPITools/Client/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs

View File

@ -0,0 +1,95 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Authenticators;
namespace Org.OpenAPITools.Client.Auth
{
/// <summary>
/// An authenticator for OAuth2 authentication flows
/// </summary>
public class OAuthAuthenticator : AuthenticatorBase
{
readonly string _tokenUrl;
readonly string _clientId;
readonly string _clientSecret;
readonly string _grantType;
readonly JsonSerializerSettings _serializerSettings;
readonly IReadableConfiguration _configuration;
/// <summary>
/// Initialize the OAuth2 Authenticator
/// </summary>
public OAuthAuthenticator(
string tokenUrl,
string clientId,
string clientSecret,
OAuthFlow? flow,
JsonSerializerSettings serializerSettings,
IReadableConfiguration configuration) : base("")
{
_tokenUrl = tokenUrl;
_clientId = clientId;
_clientSecret = clientSecret;
_serializerSettings = serializerSettings;
_configuration = configuration;
switch (flow)
{
/*case OAuthFlow.ACCESS_CODE:
_grantType = "authorization_code";
break;
case OAuthFlow.IMPLICIT:
_grantType = "implicit";
break;
case OAuthFlow.PASSWORD:
_grantType = "password";
break;*/
case OAuthFlow.APPLICATION:
_grantType = "client_credentials";
break;
default:
break;
}
}
/// <summary>
/// Creates an authentication parameter from an access token.
/// </summary>
/// <param name="accessToken">Access token to create a parameter from.</param>
/// <returns>An authentication parameter.</returns>
protected override async ValueTask<Parameter> GetAuthenticationParameter(string accessToken)
{
var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token;
return new HeaderParameter(KnownHeaders.Authorization, token);
}
/// <summary>
/// Gets the token from the OAuth2 server.
/// </summary>
/// <returns>An authentication token.</returns>
async Task<string> GetToken()
{
var client = new RestClient(_tokenUrl)
.UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration));
var request = new RestRequest()
.AddParameter("grant_type", _grantType)
.AddParameter("client_id", _clientId)
.AddParameter("client_secret", _clientSecret);
var response = await client.PostAsync<TokenResponse>(request);
return $"{response.TokenType} {response.AccessToken}";
}
}
}

View File

@ -0,0 +1,27 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
namespace Org.OpenAPITools.Client.Auth
{
/// <summary>
/// Available flows for OAuth2 authentication
/// </summary>
public enum OAuthFlow
{
/// <summary>Authorization code flow</summary>
ACCESS_CODE,
/// <summary>Implicit flow</summary>
IMPLICIT,
/// <summary>Password flow</summary>
PASSWORD,
/// <summary>Client credentials flow</summary>
APPLICATION
}
}

View File

@ -0,0 +1,22 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Newtonsoft.Json;
namespace Org.OpenAPITools.Client.Auth
{
class TokenResponse
{
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("access_token")]
public string AccessToken { get; set; }
}
}

View File

@ -17,6 +17,8 @@ using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Net.Http;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
@ -113,7 +115,7 @@ namespace Org.OpenAPITools.Client
public Configuration()
{
Proxy = null;
UserAgent = "OpenAPI-Generator/1.0.0/csharp";
UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp");
BasePath = "http://petstore.swagger.io:80/v2";
DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>();
@ -361,6 +363,30 @@ namespace Org.OpenAPITools.Client
/// <value>The access token.</value>
public virtual string AccessToken { get; set; }
/// <summary>
/// Gets or sets the token URL for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Token URL.</value>
public virtual string OAuthTokenUrl { get; set; }
/// <summary>
/// Gets or sets the client ID for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Client ID.</value>
public virtual string OAuthClientId { get; set; }
/// <summary>
/// Gets or sets the client secret for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Client Secret.</value>
public virtual string OAuthClientSecret { get; set; }
/// <summary>
/// Gets or sets the flow for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Flow.</value>
public virtual OAuthFlow? OAuthFlow { get; set; }
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
@ -684,6 +710,10 @@ namespace Org.OpenAPITools.Client
Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken,
OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl,
OAuthClientId = second.OAuthClientId ?? first.OAuthClientId,
OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret,
OAuthFlow = second.OAuthFlow ?? first.OAuthFlow,
HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat,

View File

@ -12,6 +12,7 @@ using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client
/// <value>Access token.</value>
string AccessToken { get; }
/// <summary>
/// Gets the OAuth token URL.
/// </summary>
/// <value>OAuth Token URL.</value>
string OAuthTokenUrl { get; }
/// <summary>
/// Gets the OAuth client ID.
/// </summary>
/// <value>OAuth Client ID.</value>
string OAuthClientId { get; }
/// <summary>
/// Gets the OAuth client secret.
/// </summary>
/// <value>OAuth Client Secret.</value>
string OAuthClientSecret { get; }
/// <summary>
/// Gets the OAuth flow.
/// </summary>
/// <value>OAuth Flow.</value>
OAuthFlow? OAuthFlow { get; }
/// <summary>
/// Gets the API key.
/// </summary>

View File

@ -21,7 +21,7 @@
<ItemGroup>
<PackageReference Include="CompareNETObjects" Version="4.61.0" />
<PackageReference Include="JsonSubTypes" Version="1.8.0" />
<PackageReference Include="JsonSubTypes" Version="1.9.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Polly" Version="7.2.3" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />

View File

@ -98,6 +98,9 @@ src/Org.OpenAPITools/Api/UserApi.cs
src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.cs
src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs
src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs
src/Org.OpenAPITools/Client/Auth/TokenResponse.cs
src/Org.OpenAPITools/Client/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api
@ -674,10 +675,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<Object>("/pet", localVarRequestOptions, this.Configuration);
@ -769,10 +780,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<Object>("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -844,10 +865,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Delete<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration);
@ -921,10 +952,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.DeleteAsync<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1015,10 +1056,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Get<List<Pet>>("/pet/findByStatus", localVarRequestOptions, this.Configuration);
@ -1111,10 +1162,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<List<Pet>>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1207,10 +1268,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Get<List<Pet>>("/pet/findByTags", localVarRequestOptions, this.Configuration);
@ -1305,10 +1376,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<List<Pet>>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1542,10 +1623,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Put<Object>("/pet", localVarRequestOptions, this.Configuration);
@ -1637,10 +1728,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PutAsync<Object>("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1719,10 +1820,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration);
@ -1803,10 +1914,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1887,10 +2008,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<ApiResponse>("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration);
@ -1973,10 +2104,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<ApiResponse>("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -2061,10 +2202,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<ApiResponse>("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration);
@ -2151,10 +2302,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<ApiResponse>("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -25,18 +25,18 @@ using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp;
using RestSharp.Deserializers;
using RestSharp.Serializers;
using RestSharpMethod = RestSharp.Method;
using Polly;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer
internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer
{
private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json";
@ -82,7 +82,9 @@ namespace Org.OpenAPITools.Client
}
}
public T Deserialize<T>(IRestResponse response)
public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);
public T Deserialize<T>(RestResponse response)
{
var result = (T)Deserialize(response, typeof(T));
return result;
@ -94,7 +96,7 @@ namespace Org.OpenAPITools.Client
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
internal object Deserialize(IRestResponse response, Type type)
internal object Deserialize(RestResponse response, Type type)
{
if (type == typeof(byte[])) // return byte array
{
@ -147,15 +149,22 @@ namespace Org.OpenAPITools.Client
}
}
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public ISerializer Serializer => this;
public IDeserializer Deserializer => this;
public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept;
public SupportsContentType SupportsContentType => contentType =>
contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) ||
contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase);
public string ContentType
{
get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); }
}
public DataFormat DataFormat => DataFormat.Json;
}
/// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementations),
@ -186,14 +195,14 @@ namespace Org.OpenAPITools.Client
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request);
partial void InterceptRequest(RestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
partial void InterceptResponse(RestRequest request, RestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url.
@ -228,25 +237,25 @@ namespace Org.OpenAPITools.Client
switch (method)
{
case HttpMethod.Get:
other = RestSharpMethod.GET;
other = RestSharpMethod.Get;
break;
case HttpMethod.Post:
other = RestSharpMethod.POST;
other = RestSharpMethod.Post;
break;
case HttpMethod.Put:
other = RestSharpMethod.PUT;
other = RestSharpMethod.Put;
break;
case HttpMethod.Delete:
other = RestSharpMethod.DELETE;
other = RestSharpMethod.Delete;
break;
case HttpMethod.Head:
other = RestSharpMethod.HEAD;
other = RestSharpMethod.Head;
break;
case HttpMethod.Options:
other = RestSharpMethod.OPTIONS;
other = RestSharpMethod.Options;
break;
case HttpMethod.Patch:
other = RestSharpMethod.PATCH;
other = RestSharpMethod.Patch;
break;
default:
throw new ArgumentOutOfRangeException("method", method, null);
@ -277,11 +286,7 @@ namespace Org.OpenAPITools.Client
if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method))
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
RestRequest request = new RestRequest(path, Method(method));
if (options.PathParameters != null)
{
@ -376,25 +381,17 @@ namespace Org.OpenAPITools.Client
var bytes = ClientUtils.ReadAsBytes(file);
var fileStream = file as FileStream;
if (fileStream != null)
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)));
request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name));
else
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided"));
request.AddFile(fileParam.Key, bytes, "no_file_name_provided");
}
}
}
if (options.Cookies != null && options.Cookies.Count > 0)
{
foreach (var cookie in options.Cookies)
{
request.AddCookie(cookie.Name, cookie.Value);
}
}
return request;
}
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response)
private ApiResponse<T> ToApiResponse<T>(RestResponse<T> response)
{
T result = response.Data;
string rawContent = response.Content;
@ -413,9 +410,17 @@ namespace Org.OpenAPITools.Client
}
}
if (response.ContentHeaders != null)
{
foreach (var responseHeader in response.ContentHeaders)
{
transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value));
}
}
if (response.Cookies != null)
{
foreach (var responseCookies in response.Cookies)
foreach (var responseCookies in response.Cookies.Cast<Cookie>())
{
transformed.Cookies.Add(
new Cookie(
@ -433,54 +438,46 @@ namespace Org.OpenAPITools.Client
private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration)
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
var cookies = new CookieContainer();
if (options.Cookies != null && options.Cookies.Count > 0)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
foreach (var cookie in options.Cookies)
{
cookies.Add(new Cookie(cookie.Name, cookie.Value));
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
var clientOptions = new RestClientOptions(baseUrl)
{
client.Proxy = configuration.Proxy;
}
ClientCertificates = configuration.ClientCertificates,
CookieContainer = cookies,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
RestClient client = new RestClient(clientOptions)
.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
if (configuration.ClientCertificates != null)
if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(configuration.OAuthClientId) &&
!string.IsNullOrEmpty(configuration.OAuthClientSecret) &&
configuration.OAuthFlow != null)
{
client.ClientCertificates = configuration.ClientCertificates;
client = client.UseAuthenticator(new OAuthAuthenticator(
configuration.OAuthTokenUrl,
configuration.OAuthClientId,
configuration.OAuthClientSecret,
configuration.OAuthFlow,
SerializerSettings,
configuration));
}
InterceptRequest(req);
IRestResponse<T> response;
RestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null)
{
var policy = RetryConfiguration.RetryPolicy;
@ -528,7 +525,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,
@ -557,54 +554,35 @@ namespace Org.OpenAPITools.Client
private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
var clientOptions = new RestClientOptions(baseUrl)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
}
else
ClientCertificates = configuration.ClientCertificates,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
RestClient client = new RestClient(clientOptions)
.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(configuration.OAuthClientId) &&
!string.IsNullOrEmpty(configuration.OAuthClientSecret) &&
configuration.OAuthFlow != null)
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
client = client.UseAuthenticator(new OAuthAuthenticator(
configuration.OAuthTokenUrl,
configuration.OAuthClientId,
configuration.OAuthClientSecret,
configuration.OAuthFlow,
SerializerSettings,
configuration));
}
InterceptRequest(req);
IRestResponse<T> response;
RestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
@ -645,7 +623,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,

View File

@ -0,0 +1,95 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Authenticators;
namespace Org.OpenAPITools.Client.Auth
{
/// <summary>
/// An authenticator for OAuth2 authentication flows
/// </summary>
public class OAuthAuthenticator : AuthenticatorBase
{
readonly string _tokenUrl;
readonly string _clientId;
readonly string _clientSecret;
readonly string _grantType;
readonly JsonSerializerSettings _serializerSettings;
readonly IReadableConfiguration _configuration;
/// <summary>
/// Initialize the OAuth2 Authenticator
/// </summary>
public OAuthAuthenticator(
string tokenUrl,
string clientId,
string clientSecret,
OAuthFlow? flow,
JsonSerializerSettings serializerSettings,
IReadableConfiguration configuration) : base("")
{
_tokenUrl = tokenUrl;
_clientId = clientId;
_clientSecret = clientSecret;
_serializerSettings = serializerSettings;
_configuration = configuration;
switch (flow)
{
/*case OAuthFlow.ACCESS_CODE:
_grantType = "authorization_code";
break;
case OAuthFlow.IMPLICIT:
_grantType = "implicit";
break;
case OAuthFlow.PASSWORD:
_grantType = "password";
break;*/
case OAuthFlow.APPLICATION:
_grantType = "client_credentials";
break;
default:
break;
}
}
/// <summary>
/// Creates an authentication parameter from an access token.
/// </summary>
/// <param name="accessToken">Access token to create a parameter from.</param>
/// <returns>An authentication parameter.</returns>
protected override async ValueTask<Parameter> GetAuthenticationParameter(string accessToken)
{
var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token;
return new HeaderParameter(KnownHeaders.Authorization, token);
}
/// <summary>
/// Gets the token from the OAuth2 server.
/// </summary>
/// <returns>An authentication token.</returns>
async Task<string> GetToken()
{
var client = new RestClient(_tokenUrl)
.UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration));
var request = new RestRequest()
.AddParameter("grant_type", _grantType)
.AddParameter("client_id", _clientId)
.AddParameter("client_secret", _clientSecret);
var response = await client.PostAsync<TokenResponse>(request);
return $"{response.TokenType} {response.AccessToken}";
}
}
}

View File

@ -0,0 +1,27 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
namespace Org.OpenAPITools.Client.Auth
{
/// <summary>
/// Available flows for OAuth2 authentication
/// </summary>
public enum OAuthFlow
{
/// <summary>Authorization code flow</summary>
ACCESS_CODE,
/// <summary>Implicit flow</summary>
IMPLICIT,
/// <summary>Password flow</summary>
PASSWORD,
/// <summary>Client credentials flow</summary>
APPLICATION
}
}

View File

@ -0,0 +1,22 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Newtonsoft.Json;
namespace Org.OpenAPITools.Client.Auth
{
class TokenResponse
{
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("access_token")]
public string AccessToken { get; set; }
}
}

View File

@ -17,6 +17,8 @@ using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Net.Http;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
@ -118,7 +120,7 @@ namespace Org.OpenAPITools.Client
public Configuration()
{
Proxy = null;
UserAgent = "OpenAPI-Generator/1.0.0/csharp";
UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp");
BasePath = "http://petstore.swagger.io:80/v2";
DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>();
@ -366,6 +368,30 @@ namespace Org.OpenAPITools.Client
/// <value>The access token.</value>
public virtual string AccessToken { get; set; }
/// <summary>
/// Gets or sets the token URL for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Token URL.</value>
public virtual string OAuthTokenUrl { get; set; }
/// <summary>
/// Gets or sets the client ID for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Client ID.</value>
public virtual string OAuthClientId { get; set; }
/// <summary>
/// Gets or sets the client secret for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Client Secret.</value>
public virtual string OAuthClientSecret { get; set; }
/// <summary>
/// Gets or sets the flow for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Flow.</value>
public virtual OAuthFlow? OAuthFlow { get; set; }
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
@ -689,6 +715,10 @@ namespace Org.OpenAPITools.Client
Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken,
OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl,
OAuthClientId = second.OAuthClientId ?? first.OAuthClientId,
OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret,
OAuthFlow = second.OAuthFlow ?? first.OAuthFlow,
HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat,

View File

@ -12,6 +12,7 @@ using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client
/// <value>Access token.</value>
string AccessToken { get; }
/// <summary>
/// Gets the OAuth token URL.
/// </summary>
/// <value>OAuth Token URL.</value>
string OAuthTokenUrl { get; }
/// <summary>
/// Gets the OAuth client ID.
/// </summary>
/// <value>OAuth Client ID.</value>
string OAuthClientId { get; }
/// <summary>
/// Gets the OAuth client secret.
/// </summary>
/// <value>OAuth Client Secret.</value>
string OAuthClientSecret { get; }
/// <summary>
/// Gets the OAuth flow.
/// </summary>
/// <value>OAuth Flow.</value>
OAuthFlow? OAuthFlow { get; }
/// <summary>
/// Gets the API key.
/// </summary>

View File

@ -68,6 +68,11 @@ namespace Org.OpenAPITools.Client
/// </summary>
public Object Data { get; set; }
/// <summary>
/// If request should be authenticated with OAuth.
/// </summary>
public bool OAuth { get; set; }
/// <summary>
/// Constructs a new instance of <see cref="RequestOptions"/>
/// </summary>

View File

@ -21,11 +21,11 @@ namespace Org.OpenAPITools.Client
/// <summary>
/// Retry policy
/// </summary>
public static Policy<IRestResponse> RetryPolicy { get; set; }
public static Policy<RestResponse> RetryPolicy { get; set; }
/// <summary>
/// Async retry policy
/// </summary>
public static AsyncPolicy<IRestResponse> AsyncRetryPolicy { get; set; }
public static AsyncPolicy<RestResponse> AsyncRetryPolicy { get; set; }
}
}

View File

@ -21,9 +21,9 @@
<ItemGroup>
<PackageReference Include="CompareNETObjects" Version="4.61.0" />
<PackageReference Include="JsonSubTypes" Version="1.8.0" />
<PackageReference Include="JsonSubTypes" Version="1.9.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="RestSharp" Version="106.13.0" />
<PackageReference Include="RestSharp" Version="108.0.1" />
<PackageReference Include="Polly" Version="7.2.3" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup>

View File

@ -98,6 +98,9 @@ src/Org.OpenAPITools/Api/UserApi.cs
src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.cs
src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs
src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs
src/Org.OpenAPITools/Client/Auth/TokenResponse.cs
src/Org.OpenAPITools/Client/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api
@ -674,10 +675,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<Object>("/pet", localVarRequestOptions, this.Configuration);
@ -769,10 +780,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<Object>("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -844,10 +865,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Delete<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration);
@ -921,10 +952,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.DeleteAsync<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1015,10 +1056,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Get<List<Pet>>("/pet/findByStatus", localVarRequestOptions, this.Configuration);
@ -1111,10 +1162,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<List<Pet>>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1207,10 +1268,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Get<List<Pet>>("/pet/findByTags", localVarRequestOptions, this.Configuration);
@ -1305,10 +1376,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<List<Pet>>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1542,10 +1623,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Put<Object>("/pet", localVarRequestOptions, this.Configuration);
@ -1637,10 +1728,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PutAsync<Object>("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1719,10 +1820,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration);
@ -1803,10 +1914,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1887,10 +2008,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<ApiResponse>("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration);
@ -1973,10 +2104,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<ApiResponse>("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -2061,10 +2202,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<ApiResponse>("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration);
@ -2151,10 +2302,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<ApiResponse>("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -25,18 +25,18 @@ using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp;
using RestSharp.Deserializers;
using RestSharp.Serializers;
using RestSharpMethod = RestSharp.Method;
using Polly;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer
internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer
{
private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json";
@ -82,7 +82,9 @@ namespace Org.OpenAPITools.Client
}
}
public T Deserialize<T>(IRestResponse response)
public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);
public T Deserialize<T>(RestResponse response)
{
var result = (T)Deserialize(response, typeof(T));
return result;
@ -94,7 +96,7 @@ namespace Org.OpenAPITools.Client
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
internal object Deserialize(IRestResponse response, Type type)
internal object Deserialize(RestResponse response, Type type)
{
if (type == typeof(byte[])) // return byte array
{
@ -147,15 +149,22 @@ namespace Org.OpenAPITools.Client
}
}
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public ISerializer Serializer => this;
public IDeserializer Deserializer => this;
public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept;
public SupportsContentType SupportsContentType => contentType =>
contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) ||
contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase);
public string ContentType
{
get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); }
}
public DataFormat DataFormat => DataFormat.Json;
}
/// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementations),
@ -186,14 +195,14 @@ namespace Org.OpenAPITools.Client
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request);
partial void InterceptRequest(RestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
partial void InterceptResponse(RestRequest request, RestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url.
@ -228,25 +237,25 @@ namespace Org.OpenAPITools.Client
switch (method)
{
case HttpMethod.Get:
other = RestSharpMethod.GET;
other = RestSharpMethod.Get;
break;
case HttpMethod.Post:
other = RestSharpMethod.POST;
other = RestSharpMethod.Post;
break;
case HttpMethod.Put:
other = RestSharpMethod.PUT;
other = RestSharpMethod.Put;
break;
case HttpMethod.Delete:
other = RestSharpMethod.DELETE;
other = RestSharpMethod.Delete;
break;
case HttpMethod.Head:
other = RestSharpMethod.HEAD;
other = RestSharpMethod.Head;
break;
case HttpMethod.Options:
other = RestSharpMethod.OPTIONS;
other = RestSharpMethod.Options;
break;
case HttpMethod.Patch:
other = RestSharpMethod.PATCH;
other = RestSharpMethod.Patch;
break;
default:
throw new ArgumentOutOfRangeException("method", method, null);
@ -277,11 +286,7 @@ namespace Org.OpenAPITools.Client
if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method))
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
RestRequest request = new RestRequest(path, Method(method));
if (options.PathParameters != null)
{
@ -376,25 +381,17 @@ namespace Org.OpenAPITools.Client
var bytes = ClientUtils.ReadAsBytes(file);
var fileStream = file as FileStream;
if (fileStream != null)
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)));
request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name));
else
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided"));
request.AddFile(fileParam.Key, bytes, "no_file_name_provided");
}
}
}
if (options.Cookies != null && options.Cookies.Count > 0)
{
foreach (var cookie in options.Cookies)
{
request.AddCookie(cookie.Name, cookie.Value);
}
}
return request;
}
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response)
private ApiResponse<T> ToApiResponse<T>(RestResponse<T> response)
{
T result = response.Data;
string rawContent = response.Content;
@ -413,9 +410,17 @@ namespace Org.OpenAPITools.Client
}
}
if (response.ContentHeaders != null)
{
foreach (var responseHeader in response.ContentHeaders)
{
transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value));
}
}
if (response.Cookies != null)
{
foreach (var responseCookies in response.Cookies)
foreach (var responseCookies in response.Cookies.Cast<Cookie>())
{
transformed.Cookies.Add(
new Cookie(
@ -433,54 +438,46 @@ namespace Org.OpenAPITools.Client
private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration)
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
var cookies = new CookieContainer();
if (options.Cookies != null && options.Cookies.Count > 0)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
foreach (var cookie in options.Cookies)
{
cookies.Add(new Cookie(cookie.Name, cookie.Value));
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
var clientOptions = new RestClientOptions(baseUrl)
{
client.Proxy = configuration.Proxy;
}
ClientCertificates = configuration.ClientCertificates,
CookieContainer = cookies,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
RestClient client = new RestClient(clientOptions)
.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
if (configuration.ClientCertificates != null)
if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(configuration.OAuthClientId) &&
!string.IsNullOrEmpty(configuration.OAuthClientSecret) &&
configuration.OAuthFlow != null)
{
client.ClientCertificates = configuration.ClientCertificates;
client = client.UseAuthenticator(new OAuthAuthenticator(
configuration.OAuthTokenUrl,
configuration.OAuthClientId,
configuration.OAuthClientSecret,
configuration.OAuthFlow,
SerializerSettings,
configuration));
}
InterceptRequest(req);
IRestResponse<T> response;
RestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null)
{
var policy = RetryConfiguration.RetryPolicy;
@ -528,7 +525,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,
@ -557,54 +554,35 @@ namespace Org.OpenAPITools.Client
private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
var clientOptions = new RestClientOptions(baseUrl)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
}
else
ClientCertificates = configuration.ClientCertificates,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
RestClient client = new RestClient(clientOptions)
.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(configuration.OAuthClientId) &&
!string.IsNullOrEmpty(configuration.OAuthClientSecret) &&
configuration.OAuthFlow != null)
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
client = client.UseAuthenticator(new OAuthAuthenticator(
configuration.OAuthTokenUrl,
configuration.OAuthClientId,
configuration.OAuthClientSecret,
configuration.OAuthFlow,
SerializerSettings,
configuration));
}
InterceptRequest(req);
IRestResponse<T> response;
RestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
@ -645,7 +623,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,

View File

@ -0,0 +1,95 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Authenticators;
namespace Org.OpenAPITools.Client.Auth
{
/// <summary>
/// An authenticator for OAuth2 authentication flows
/// </summary>
public class OAuthAuthenticator : AuthenticatorBase
{
readonly string _tokenUrl;
readonly string _clientId;
readonly string _clientSecret;
readonly string _grantType;
readonly JsonSerializerSettings _serializerSettings;
readonly IReadableConfiguration _configuration;
/// <summary>
/// Initialize the OAuth2 Authenticator
/// </summary>
public OAuthAuthenticator(
string tokenUrl,
string clientId,
string clientSecret,
OAuthFlow? flow,
JsonSerializerSettings serializerSettings,
IReadableConfiguration configuration) : base("")
{
_tokenUrl = tokenUrl;
_clientId = clientId;
_clientSecret = clientSecret;
_serializerSettings = serializerSettings;
_configuration = configuration;
switch (flow)
{
/*case OAuthFlow.ACCESS_CODE:
_grantType = "authorization_code";
break;
case OAuthFlow.IMPLICIT:
_grantType = "implicit";
break;
case OAuthFlow.PASSWORD:
_grantType = "password";
break;*/
case OAuthFlow.APPLICATION:
_grantType = "client_credentials";
break;
default:
break;
}
}
/// <summary>
/// Creates an authentication parameter from an access token.
/// </summary>
/// <param name="accessToken">Access token to create a parameter from.</param>
/// <returns>An authentication parameter.</returns>
protected override async ValueTask<Parameter> GetAuthenticationParameter(string accessToken)
{
var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token;
return new HeaderParameter(KnownHeaders.Authorization, token);
}
/// <summary>
/// Gets the token from the OAuth2 server.
/// </summary>
/// <returns>An authentication token.</returns>
async Task<string> GetToken()
{
var client = new RestClient(_tokenUrl)
.UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration));
var request = new RestRequest()
.AddParameter("grant_type", _grantType)
.AddParameter("client_id", _clientId)
.AddParameter("client_secret", _clientSecret);
var response = await client.PostAsync<TokenResponse>(request);
return $"{response.TokenType} {response.AccessToken}";
}
}
}

View File

@ -0,0 +1,27 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
namespace Org.OpenAPITools.Client.Auth
{
/// <summary>
/// Available flows for OAuth2 authentication
/// </summary>
public enum OAuthFlow
{
/// <summary>Authorization code flow</summary>
ACCESS_CODE,
/// <summary>Implicit flow</summary>
IMPLICIT,
/// <summary>Password flow</summary>
PASSWORD,
/// <summary>Client credentials flow</summary>
APPLICATION
}
}

View File

@ -0,0 +1,22 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Newtonsoft.Json;
namespace Org.OpenAPITools.Client.Auth
{
class TokenResponse
{
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("access_token")]
public string AccessToken { get; set; }
}
}

View File

@ -17,6 +17,8 @@ using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Net.Http;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
@ -118,7 +120,7 @@ namespace Org.OpenAPITools.Client
public Configuration()
{
Proxy = null;
UserAgent = "OpenAPI-Generator/1.0.0/csharp";
UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp");
BasePath = "http://petstore.swagger.io:80/v2";
DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>();
@ -366,6 +368,30 @@ namespace Org.OpenAPITools.Client
/// <value>The access token.</value>
public virtual string AccessToken { get; set; }
/// <summary>
/// Gets or sets the token URL for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Token URL.</value>
public virtual string OAuthTokenUrl { get; set; }
/// <summary>
/// Gets or sets the client ID for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Client ID.</value>
public virtual string OAuthClientId { get; set; }
/// <summary>
/// Gets or sets the client secret for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Client Secret.</value>
public virtual string OAuthClientSecret { get; set; }
/// <summary>
/// Gets or sets the flow for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Flow.</value>
public virtual OAuthFlow? OAuthFlow { get; set; }
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
@ -689,6 +715,10 @@ namespace Org.OpenAPITools.Client
Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken,
OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl,
OAuthClientId = second.OAuthClientId ?? first.OAuthClientId,
OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret,
OAuthFlow = second.OAuthFlow ?? first.OAuthFlow,
HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat,

View File

@ -12,6 +12,7 @@ using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client
/// <value>Access token.</value>
string AccessToken { get; }
/// <summary>
/// Gets the OAuth token URL.
/// </summary>
/// <value>OAuth Token URL.</value>
string OAuthTokenUrl { get; }
/// <summary>
/// Gets the OAuth client ID.
/// </summary>
/// <value>OAuth Client ID.</value>
string OAuthClientId { get; }
/// <summary>
/// Gets the OAuth client secret.
/// </summary>
/// <value>OAuth Client Secret.</value>
string OAuthClientSecret { get; }
/// <summary>
/// Gets the OAuth flow.
/// </summary>
/// <value>OAuth Flow.</value>
OAuthFlow? OAuthFlow { get; }
/// <summary>
/// Gets the API key.
/// </summary>

View File

@ -68,6 +68,11 @@ namespace Org.OpenAPITools.Client
/// </summary>
public Object Data { get; set; }
/// <summary>
/// If request should be authenticated with OAuth.
/// </summary>
public bool OAuth { get; set; }
/// <summary>
/// Constructs a new instance of <see cref="RequestOptions"/>
/// </summary>

View File

@ -21,11 +21,11 @@ namespace Org.OpenAPITools.Client
/// <summary>
/// Retry policy
/// </summary>
public static Policy<IRestResponse> RetryPolicy { get; set; }
public static Policy<RestResponse> RetryPolicy { get; set; }
/// <summary>
/// Async retry policy
/// </summary>
public static AsyncPolicy<IRestResponse> AsyncRetryPolicy { get; set; }
public static AsyncPolicy<RestResponse> AsyncRetryPolicy { get; set; }
}
}

View File

@ -21,9 +21,9 @@
<ItemGroup>
<PackageReference Include="CompareNETObjects" Version="4.61.0" />
<PackageReference Include="JsonSubTypes" Version="1.8.0" />
<PackageReference Include="JsonSubTypes" Version="1.9.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="RestSharp" Version="106.13.0" />
<PackageReference Include="RestSharp" Version="108.0.1" />
<PackageReference Include="Polly" Version="7.2.3" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup>

View File

@ -97,6 +97,9 @@ src/Org.OpenAPITools/Api/UserApi.cs
src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.cs
src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs
src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs
src/Org.OpenAPITools/Client/Auth/TokenResponse.cs
src/Org.OpenAPITools/Client/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs

View File

@ -10,7 +10,7 @@ OpenAPI spec version: 1.0.0
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api
@ -674,10 +675,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<Object>("/pet", localVarRequestOptions, this.Configuration);
@ -769,10 +780,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<Object>("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -844,10 +865,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Delete<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration);
@ -921,10 +952,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.DeleteAsync<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1015,10 +1056,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Get<List<Pet>>("/pet/findByStatus", localVarRequestOptions, this.Configuration);
@ -1111,10 +1162,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<List<Pet>>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1207,10 +1268,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Get<List<Pet>>("/pet/findByTags", localVarRequestOptions, this.Configuration);
@ -1305,10 +1376,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<List<Pet>>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1542,10 +1623,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Put<Object>("/pet", localVarRequestOptions, this.Configuration);
@ -1637,10 +1728,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PutAsync<Object>("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1719,10 +1820,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration);
@ -1803,10 +1914,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1887,10 +2008,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<ApiResponse>("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration);
@ -1973,10 +2104,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<ApiResponse>("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -2061,10 +2202,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<ApiResponse>("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration);
@ -2151,10 +2302,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<ApiResponse>("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -24,18 +24,18 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp;
using RestSharp.Deserializers;
using RestSharp.Serializers;
using RestSharpMethod = RestSharp.Method;
using Polly;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer
internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer
{
private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json";
@ -81,7 +81,9 @@ namespace Org.OpenAPITools.Client
}
}
public T Deserialize<T>(IRestResponse response)
public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);
public T Deserialize<T>(RestResponse response)
{
var result = (T)Deserialize(response, typeof(T));
return result;
@ -93,7 +95,7 @@ namespace Org.OpenAPITools.Client
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
internal object Deserialize(IRestResponse response, Type type)
internal object Deserialize(RestResponse response, Type type)
{
if (type == typeof(byte[])) // return byte array
{
@ -146,15 +148,22 @@ namespace Org.OpenAPITools.Client
}
}
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public ISerializer Serializer => this;
public IDeserializer Deserializer => this;
public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept;
public SupportsContentType SupportsContentType => contentType =>
contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) ||
contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase);
public string ContentType
{
get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); }
}
public DataFormat DataFormat => DataFormat.Json;
}
/// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementations),
@ -185,14 +194,14 @@ namespace Org.OpenAPITools.Client
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request);
partial void InterceptRequest(RestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
partial void InterceptResponse(RestRequest request, RestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url.
@ -227,25 +236,25 @@ namespace Org.OpenAPITools.Client
switch (method)
{
case HttpMethod.Get:
other = RestSharpMethod.GET;
other = RestSharpMethod.Get;
break;
case HttpMethod.Post:
other = RestSharpMethod.POST;
other = RestSharpMethod.Post;
break;
case HttpMethod.Put:
other = RestSharpMethod.PUT;
other = RestSharpMethod.Put;
break;
case HttpMethod.Delete:
other = RestSharpMethod.DELETE;
other = RestSharpMethod.Delete;
break;
case HttpMethod.Head:
other = RestSharpMethod.HEAD;
other = RestSharpMethod.Head;
break;
case HttpMethod.Options:
other = RestSharpMethod.OPTIONS;
other = RestSharpMethod.Options;
break;
case HttpMethod.Patch:
other = RestSharpMethod.PATCH;
other = RestSharpMethod.Patch;
break;
default:
throw new ArgumentOutOfRangeException("method", method, null);
@ -276,11 +285,7 @@ namespace Org.OpenAPITools.Client
if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method))
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
RestRequest request = new RestRequest(path, Method(method));
if (options.PathParameters != null)
{
@ -375,25 +380,17 @@ namespace Org.OpenAPITools.Client
var bytes = ClientUtils.ReadAsBytes(file);
var fileStream = file as FileStream;
if (fileStream != null)
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)));
request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name));
else
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided"));
request.AddFile(fileParam.Key, bytes, "no_file_name_provided");
}
}
}
if (options.Cookies != null && options.Cookies.Count > 0)
{
foreach (var cookie in options.Cookies)
{
request.AddCookie(cookie.Name, cookie.Value);
}
}
return request;
}
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response)
private ApiResponse<T> ToApiResponse<T>(RestResponse<T> response)
{
T result = response.Data;
string rawContent = response.Content;
@ -412,9 +409,17 @@ namespace Org.OpenAPITools.Client
}
}
if (response.ContentHeaders != null)
{
foreach (var responseHeader in response.ContentHeaders)
{
transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value));
}
}
if (response.Cookies != null)
{
foreach (var responseCookies in response.Cookies)
foreach (var responseCookies in response.Cookies.Cast<Cookie>())
{
transformed.Cookies.Add(
new Cookie(
@ -432,54 +437,46 @@ namespace Org.OpenAPITools.Client
private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration)
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
var cookies = new CookieContainer();
if (options.Cookies != null && options.Cookies.Count > 0)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
foreach (var cookie in options.Cookies)
{
cookies.Add(new Cookie(cookie.Name, cookie.Value));
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
var clientOptions = new RestClientOptions(baseUrl)
{
client.Proxy = configuration.Proxy;
}
ClientCertificates = configuration.ClientCertificates,
CookieContainer = cookies,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
RestClient client = new RestClient(clientOptions)
.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
if (configuration.ClientCertificates != null)
if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(configuration.OAuthClientId) &&
!string.IsNullOrEmpty(configuration.OAuthClientSecret) &&
configuration.OAuthFlow != null)
{
client.ClientCertificates = configuration.ClientCertificates;
client = client.UseAuthenticator(new OAuthAuthenticator(
configuration.OAuthTokenUrl,
configuration.OAuthClientId,
configuration.OAuthClientSecret,
configuration.OAuthFlow,
SerializerSettings,
configuration));
}
InterceptRequest(req);
IRestResponse<T> response;
RestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null)
{
var policy = RetryConfiguration.RetryPolicy;
@ -527,7 +524,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,
@ -556,54 +553,35 @@ namespace Org.OpenAPITools.Client
private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
var clientOptions = new RestClientOptions(baseUrl)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
}
else
ClientCertificates = configuration.ClientCertificates,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
RestClient client = new RestClient(clientOptions)
.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(configuration.OAuthClientId) &&
!string.IsNullOrEmpty(configuration.OAuthClientSecret) &&
configuration.OAuthFlow != null)
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
client = client.UseAuthenticator(new OAuthAuthenticator(
configuration.OAuthTokenUrl,
configuration.OAuthClientId,
configuration.OAuthClientSecret,
configuration.OAuthFlow,
SerializerSettings,
configuration));
}
InterceptRequest(req);
IRestResponse<T> response;
RestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
@ -644,7 +622,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,

View File

@ -0,0 +1,95 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Authenticators;
namespace Org.OpenAPITools.Client.Auth
{
/// <summary>
/// An authenticator for OAuth2 authentication flows
/// </summary>
public class OAuthAuthenticator : AuthenticatorBase
{
readonly string _tokenUrl;
readonly string _clientId;
readonly string _clientSecret;
readonly string _grantType;
readonly JsonSerializerSettings _serializerSettings;
readonly IReadableConfiguration _configuration;
/// <summary>
/// Initialize the OAuth2 Authenticator
/// </summary>
public OAuthAuthenticator(
string tokenUrl,
string clientId,
string clientSecret,
OAuthFlow? flow,
JsonSerializerSettings serializerSettings,
IReadableConfiguration configuration) : base("")
{
_tokenUrl = tokenUrl;
_clientId = clientId;
_clientSecret = clientSecret;
_serializerSettings = serializerSettings;
_configuration = configuration;
switch (flow)
{
/*case OAuthFlow.ACCESS_CODE:
_grantType = "authorization_code";
break;
case OAuthFlow.IMPLICIT:
_grantType = "implicit";
break;
case OAuthFlow.PASSWORD:
_grantType = "password";
break;*/
case OAuthFlow.APPLICATION:
_grantType = "client_credentials";
break;
default:
break;
}
}
/// <summary>
/// Creates an authentication parameter from an access token.
/// </summary>
/// <param name="accessToken">Access token to create a parameter from.</param>
/// <returns>An authentication parameter.</returns>
protected override async ValueTask<Parameter> GetAuthenticationParameter(string accessToken)
{
var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token;
return new HeaderParameter(KnownHeaders.Authorization, token);
}
/// <summary>
/// Gets the token from the OAuth2 server.
/// </summary>
/// <returns>An authentication token.</returns>
async Task<string> GetToken()
{
var client = new RestClient(_tokenUrl)
.UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration));
var request = new RestRequest()
.AddParameter("grant_type", _grantType)
.AddParameter("client_id", _clientId)
.AddParameter("client_secret", _clientSecret);
var response = await client.PostAsync<TokenResponse>(request);
return $"{response.TokenType} {response.AccessToken}";
}
}
}

View File

@ -0,0 +1,27 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
namespace Org.OpenAPITools.Client.Auth
{
/// <summary>
/// Available flows for OAuth2 authentication
/// </summary>
public enum OAuthFlow
{
/// <summary>Authorization code flow</summary>
ACCESS_CODE,
/// <summary>Implicit flow</summary>
IMPLICIT,
/// <summary>Password flow</summary>
PASSWORD,
/// <summary>Client credentials flow</summary>
APPLICATION
}
}

View File

@ -0,0 +1,22 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Newtonsoft.Json;
namespace Org.OpenAPITools.Client.Auth
{
class TokenResponse
{
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("access_token")]
public string AccessToken { get; set; }
}
}

View File

@ -17,6 +17,8 @@ using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Net.Http;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
@ -113,7 +115,7 @@ namespace Org.OpenAPITools.Client
public Configuration()
{
Proxy = null;
UserAgent = "OpenAPI-Generator/1.0.0/csharp";
UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp");
BasePath = "http://petstore.swagger.io:80/v2";
DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>();
@ -361,6 +363,30 @@ namespace Org.OpenAPITools.Client
/// <value>The access token.</value>
public virtual string AccessToken { get; set; }
/// <summary>
/// Gets or sets the token URL for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Token URL.</value>
public virtual string OAuthTokenUrl { get; set; }
/// <summary>
/// Gets or sets the client ID for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Client ID.</value>
public virtual string OAuthClientId { get; set; }
/// <summary>
/// Gets or sets the client secret for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Client Secret.</value>
public virtual string OAuthClientSecret { get; set; }
/// <summary>
/// Gets or sets the flow for OAuth2 authentication.
/// </summary>
/// <value>The OAuth Flow.</value>
public virtual OAuthFlow? OAuthFlow { get; set; }
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
@ -684,6 +710,10 @@ namespace Org.OpenAPITools.Client
Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken,
OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl,
OAuthClientId = second.OAuthClientId ?? first.OAuthClientId,
OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret,
OAuthFlow = second.OAuthFlow ?? first.OAuthFlow,
HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat,

View File

@ -12,6 +12,7 @@ using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client
{
@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client
/// <value>Access token.</value>
string AccessToken { get; }
/// <summary>
/// Gets the OAuth token URL.
/// </summary>
/// <value>OAuth Token URL.</value>
string OAuthTokenUrl { get; }
/// <summary>
/// Gets the OAuth client ID.
/// </summary>
/// <value>OAuth Client ID.</value>
string OAuthClientId { get; }
/// <summary>
/// Gets the OAuth client secret.
/// </summary>
/// <value>OAuth Client Secret.</value>
string OAuthClientSecret { get; }
/// <summary>
/// Gets the OAuth flow.
/// </summary>
/// <value>OAuth Flow.</value>
OAuthFlow? OAuthFlow { get; }
/// <summary>
/// Gets the API key.
/// </summary>

View File

@ -68,6 +68,11 @@ namespace Org.OpenAPITools.Client
/// </summary>
public Object Data { get; set; }
/// <summary>
/// If request should be authenticated with OAuth.
/// </summary>
public bool OAuth { get; set; }
/// <summary>
/// Constructs a new instance of <see cref="RequestOptions"/>
/// </summary>

View File

@ -21,11 +21,11 @@ namespace Org.OpenAPITools.Client
/// <summary>
/// Retry policy
/// </summary>
public static Policy<IRestResponse> RetryPolicy { get; set; }
public static Policy<RestResponse> RetryPolicy { get; set; }
/// <summary>
/// Async retry policy
/// </summary>
public static AsyncPolicy<IRestResponse> AsyncRetryPolicy { get; set; }
public static AsyncPolicy<RestResponse> AsyncRetryPolicy { get; set; }
}
}

View File

@ -21,9 +21,9 @@
<ItemGroup>
<PackageReference Include="CompareNETObjects" Version="4.61.0" />
<PackageReference Include="JsonSubTypes" Version="1.8.0" />
<PackageReference Include="JsonSubTypes" Version="1.9.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="RestSharp" Version="106.13.0" />
<PackageReference Include="RestSharp" Version="108.0.1" />
<PackageReference Include="Polly" Version="7.2.3" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup>

View File

@ -97,6 +97,9 @@ src/Org.OpenAPITools/Api/UserApi.cs
src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.cs
src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs
src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs
src/Org.OpenAPITools/Client/Auth/TokenResponse.cs
src/Org.OpenAPITools/Client/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api
@ -674,10 +675,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<Object>("/pet", localVarRequestOptions, this.Configuration);
@ -769,10 +780,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<Object>("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -844,10 +865,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Delete<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration);
@ -921,10 +952,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.DeleteAsync<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1015,10 +1056,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Get<List<Pet>>("/pet/findByStatus", localVarRequestOptions, this.Configuration);
@ -1111,10 +1162,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<List<Pet>>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1207,10 +1268,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Get<List<Pet>>("/pet/findByTags", localVarRequestOptions, this.Configuration);
@ -1305,10 +1376,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<List<Pet>>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1542,10 +1623,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Put<Object>("/pet", localVarRequestOptions, this.Configuration);
@ -1637,10 +1728,20 @@ namespace Org.OpenAPITools.Api
}
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PutAsync<Object>("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1719,10 +1820,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration);
@ -1803,10 +1914,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<Object>("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -1887,10 +2008,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<ApiResponse>("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration);
@ -1973,10 +2104,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<ApiResponse>("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
@ -2061,10 +2202,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = this.Client.Post<ApiResponse>("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration);
@ -2151,10 +2302,20 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
if (!string.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientId) &&
!string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) &&
this.Configuration.OAuthFlow != null)
{
localVarRequestOptions.OAuth = true;
}
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<ApiResponse>("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api

Some files were not shown because too many files have changed in this diff Show More