[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 |BearerToken|✗|OAS3
|OAuth2_Implicit|✓|OAS2,OAS3 |OAuth2_Implicit|✓|OAS2,OAS3
|OAuth2_Password|✗|OAS2,OAS3 |OAuth2_Password|✗|OAS2,OAS3
|OAuth2_ClientCredentials||OAS2,OAS3 |OAuth2_ClientCredentials||OAS2,OAS3
|OAuth2_AuthorizationCode|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3
### Wire Format Feature ### Wire Format Feature

View File

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

View File

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

View File

@ -11,6 +11,9 @@ using System.Net;
using System.Reflection; using System.Reflection;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
using System.Net.Http;
{{#hasOAuthMethods}}using {{packageName}}.Client.Auth;
{{/hasOAuthMethods}}
namespace {{packageName}}.Client namespace {{packageName}}.Client
{ {
@ -118,7 +121,7 @@ namespace {{packageName}}.Client
public Configuration() public Configuration()
{ {
Proxy = null; Proxy = null;
UserAgent = "{{httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{packageVersion}}/csharp{{/httpUserAgent}}"; UserAgent = WebUtility.UrlEncode("{{httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{packageVersion}}/csharp{{/httpUserAgent}}");
BasePath = "{{{basePath}}}"; BasePath = "{{{basePath}}}";
DefaultHeaders = new {{^net35}}Concurrent{{/net35}}Dictionary<string, string>(); DefaultHeaders = new {{^net35}}Concurrent{{/net35}}Dictionary<string, string>();
ApiKey = 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> /// <value>The access token.</value>
public virtual string AccessToken { get; set; } 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> /// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server. /// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary> /// </summary>
@ -655,6 +684,12 @@ namespace {{packageName}}.Client
Username = second.Username ?? first.Username, Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password, Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken, 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}} {{#hasHttpSignatureMethods}}
HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration, HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration,
{{/hasHttpSignatureMethods}} {{/hasHttpSignatureMethods}}

View File

@ -4,6 +4,8 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
{{#hasOAuthMethods}}using {{packageName}}.Client.Auth;
{{/hasOAuthMethods}}
namespace {{packageName}}.Client namespace {{packageName}}.Client
{ {
@ -18,6 +20,32 @@ namespace {{packageName}}.Client
/// <value>Access token.</value> /// <value>Access token.</value>
string AccessToken { get; } 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> /// <summary>
/// Gets the API key. /// Gets the API key.
/// </summary> /// </summary>

View File

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

View File

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

View File

@ -7,6 +7,8 @@ using System.Linq;
using System.Net; using System.Net;
using System.Net.Mime; using System.Net.Mime;
using {{packageName}}.Client; using {{packageName}}.Client;
{{#hasOAuthMethods}}using {{packageName}}.Client.Auth;
{{/hasOAuthMethods}}
{{#hasImport}}using {{packageName}}.{{modelPackage}}; {{#hasImport}}using {{packageName}}.{{modelPackage}};
{{/hasImport}} {{/hasImport}}
@ -438,9 +440,21 @@ namespace {{packageName}}.{{apiPackage}}
{{/isBasicBearer}} {{/isBasicBearer}}
{{#isOAuth}} {{#isOAuth}}
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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}} {{/isOAuth}}
{{#isHttpSignature}} {{#isHttpSignature}}
@ -669,9 +683,21 @@ namespace {{packageName}}.{{apiPackage}}
{{/isBasic}} {{/isBasic}}
{{#isOAuth}} {{#isOAuth}}
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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}} {{/isOAuth}}
{{#isHttpSignature}} {{#isHttpSignature}}

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" /> <PackageReference Include="CompareNETObjects" Version="4.61.0" />
{{/useCompareNetObjects}} {{/useCompareNetObjects}}
{{^useGenericHost}} {{^useGenericHost}}
<PackageReference Include="JsonSubTypes" Version="1.8.0" /> <PackageReference Include="JsonSubTypes" Version="1.9.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
{{/useGenericHost}} {{/useGenericHost}}
{{#useRestSharp}} {{#useRestSharp}}
<PackageReference Include="RestSharp" Version="106.13.0" /> <PackageReference Include="RestSharp" Version="108.0.1" />
{{/useRestSharp}} {{/useRestSharp}}
{{#useGenericHost}} {{#useGenericHost}}
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />

View File

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

View File

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

View File

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

View File

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

View File

@ -21,9 +21,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="CompareNETObjects" Version="4.61.0" /> <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="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="Polly" Version="7.2.3" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" /> <PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup> </ItemGroup>

View File

@ -98,6 +98,9 @@ src/Org.OpenAPITools/Api/UserApi.cs
src/Org.OpenAPITools/Client/ApiClient.cs src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.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/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs src/Org.OpenAPITools/Client/ExceptionFactory.cs

View File

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

View File

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

View File

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

View File

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

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net; using System.Net;
using System.Net.Mime; using System.Net.Mime;
using Org.OpenAPITools.Client; using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api namespace Org.OpenAPITools.Api
@ -674,9 +675,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -769,9 +780,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -844,9 +865,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -921,9 +952,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1015,9 +1056,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1111,9 +1162,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1207,9 +1268,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1305,9 +1376,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1542,9 +1623,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1637,9 +1728,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1719,9 +1820,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1803,9 +1914,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1887,9 +2008,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1973,9 +2104,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -2061,9 +2202,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -2151,9 +2302,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request

View File

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

View File

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

View File

@ -24,18 +24,18 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp; using RestSharp;
using RestSharp.Deserializers; using RestSharp.Serializers;
using RestSharpMethod = RestSharp.Method; using RestSharpMethod = RestSharp.Method;
using Polly; using Polly;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
/// <summary> /// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary> /// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer
{ {
private readonly IReadableConfiguration _configuration; private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json"; 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)); var result = (T)Deserialize(response, typeof(T));
return result; return result;
@ -93,7 +95,7 @@ namespace Org.OpenAPITools.Client
/// <param name="response">The HTTP response.</param> /// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param> /// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns> /// <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 if (type == typeof(byte[])) // return byte array
{ {
@ -146,15 +148,22 @@ namespace Org.OpenAPITools.Client
} }
} }
public string RootElement { get; set; } public ISerializer Serializer => this;
public string Namespace { get; set; } public IDeserializer Deserializer => this;
public string DateFormat { get; set; }
public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept;
public SupportsContentType SupportsContentType => contentType =>
contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) ||
contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase);
public string ContentType public string ContentType
{ {
get { return _contentType; } get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); } set { throw new InvalidOperationException("Not allowed to set content type."); }
} }
public DataFormat DataFormat => DataFormat.Json;
} }
/// <summary> /// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), /// 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. /// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary> /// </summary>
/// <param name="request">The RestSharp request object</param> /// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request); partial void InterceptRequest(RestRequest request);
/// <summary> /// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code. /// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary> /// </summary>
/// <param name="request">The RestSharp request object</param> /// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response 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> /// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url. /// 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) switch (method)
{ {
case HttpMethod.Get: case HttpMethod.Get:
other = RestSharpMethod.GET; other = RestSharpMethod.Get;
break; break;
case HttpMethod.Post: case HttpMethod.Post:
other = RestSharpMethod.POST; other = RestSharpMethod.Post;
break; break;
case HttpMethod.Put: case HttpMethod.Put:
other = RestSharpMethod.PUT; other = RestSharpMethod.Put;
break; break;
case HttpMethod.Delete: case HttpMethod.Delete:
other = RestSharpMethod.DELETE; other = RestSharpMethod.Delete;
break; break;
case HttpMethod.Head: case HttpMethod.Head:
other = RestSharpMethod.HEAD; other = RestSharpMethod.Head;
break; break;
case HttpMethod.Options: case HttpMethod.Options:
other = RestSharpMethod.OPTIONS; other = RestSharpMethod.Options;
break; break;
case HttpMethod.Patch: case HttpMethod.Patch:
other = RestSharpMethod.PATCH; other = RestSharpMethod.Patch;
break; break;
default: default:
throw new ArgumentOutOfRangeException("method", method, null); throw new ArgumentOutOfRangeException("method", method, null);
@ -276,11 +285,7 @@ namespace Org.OpenAPITools.Client
if (options == null) throw new ArgumentNullException("options"); if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration"); if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method)) RestRequest request = new RestRequest(path, Method(method));
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
if (options.PathParameters != null) if (options.PathParameters != null)
{ {
@ -375,25 +380,17 @@ namespace Org.OpenAPITools.Client
var bytes = ClientUtils.ReadAsBytes(file); var bytes = ClientUtils.ReadAsBytes(file);
var fileStream = file as FileStream; var fileStream = file as FileStream;
if (fileStream != null) 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 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; return request;
} }
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response) private ApiResponse<T> ToApiResponse<T>(RestResponse<T> response)
{ {
T result = response.Data; T result = response.Data;
string rawContent = response.Content; 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) if (response.Cookies != null)
{ {
foreach (var responseCookies in response.Cookies) foreach (var responseCookies in response.Cookies.Cast<Cookie>())
{ {
transformed.Cookies.Add( transformed.Cookies.Add(
new Cookie( new Cookie(
@ -432,54 +437,46 @@ namespace Org.OpenAPITools.Client
private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration) private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration)
{ {
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers(); var cookies = new CookieContainer();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null) if (options.Cookies != null && options.Cookies.Count > 0)
{ {
client.AddHandler("application/json", () => existingDeserializer); foreach (var cookie in options.Cookies)
client.AddHandler("text/json", () => existingDeserializer); {
client.AddHandler("text/x-json", () => existingDeserializer); cookies.Add(new Cookie(cookie.Name, cookie.Value));
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);
} }
var xmlDeserializer = new XmlDeserializer(); var clientOptions = new RestClientOptions(baseUrl)
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; ClientCertificates = configuration.ClientCertificates,
} CookieContainer = cookies,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
if (configuration.UserAgent != null) RestClient client = new RestClient(clientOptions)
{ .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
client.UserAgent = configuration.UserAgent;
}
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); InterceptRequest(req);
IRestResponse<T> response; RestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null) if (RetryConfiguration.RetryPolicy != null)
{ {
var policy = RetryConfiguration.RetryPolicy; var policy = RetryConfiguration.RetryPolicy;
@ -527,7 +524,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0) if (response.Cookies != null && response.Cookies.Count > 0)
{ {
if (result.Cookies == null) result.Cookies = new List<Cookie>(); 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( var cookie = new Cookie(
restResponseCookie.Name, 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)) 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; var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers(); var clientOptions = new RestClientOptions(baseUrl)
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
{ {
client.AddHandler("application/json", () => existingDeserializer); ClientCertificates = configuration.ClientCertificates,
client.AddHandler("text/json", () => existingDeserializer); MaxTimeout = configuration.Timeout,
client.AddHandler("text/x-json", () => existingDeserializer); Proxy = configuration.Proxy,
client.AddHandler("text/javascript", () => existingDeserializer); UserAgent = configuration.UserAgent
client.AddHandler("*+json", () => existingDeserializer); };
}
else 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 = client.UseAuthenticator(new OAuthAuthenticator(
client.AddHandler("application/json", () => customDeserializer); configuration.OAuthTokenUrl,
client.AddHandler("text/json", () => customDeserializer); configuration.OAuthClientId,
client.AddHandler("text/x-json", () => customDeserializer); configuration.OAuthClientSecret,
client.AddHandler("text/javascript", () => customDeserializer); configuration.OAuthFlow,
client.AddHandler("*+json", () => customDeserializer); SerializerSettings,
} configuration));
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;
} }
InterceptRequest(req); InterceptRequest(req);
IRestResponse<T> response; RestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null) if (RetryConfiguration.AsyncRetryPolicy != null)
{ {
var policy = RetryConfiguration.AsyncRetryPolicy; var policy = RetryConfiguration.AsyncRetryPolicy;
@ -644,7 +622,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0) if (response.Cookies != null && response.Cookies.Count > 0)
{ {
if (result.Cookies == null) result.Cookies = new List<Cookie>(); 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( var cookie = new Cookie(
restResponseCookie.Name, 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.Reflection;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
using System.Net.Http;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
@ -113,7 +115,7 @@ namespace Org.OpenAPITools.Client
public Configuration() public Configuration()
{ {
Proxy = null; 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"; BasePath = "http://petstore.swagger.io:80/v2";
DefaultHeaders = new ConcurrentDictionary<string, string>(); DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>(); ApiKey = new ConcurrentDictionary<string, string>();
@ -361,6 +363,30 @@ namespace Org.OpenAPITools.Client
/// <value>The access token.</value> /// <value>The access token.</value>
public virtual string AccessToken { get; set; } 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> /// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server. /// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary> /// </summary>
@ -684,6 +710,10 @@ namespace Org.OpenAPITools.Client
Username = second.Username ?? first.Username, Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password, Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken, 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, HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat,

View File

@ -12,6 +12,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client
/// <value>Access token.</value> /// <value>Access token.</value>
string AccessToken { get; } 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> /// <summary>
/// Gets the API key. /// Gets the API key.
/// </summary> /// </summary>

View File

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

View File

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

View File

@ -21,9 +21,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="CompareNETObjects" Version="4.61.0" /> <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="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="Polly" Version="7.2.3" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" /> <PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup> </ItemGroup>

View File

@ -97,6 +97,9 @@ src/Org.OpenAPITools/Api/UserApi.cs
src/Org.OpenAPITools/Client/ApiClient.cs src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.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/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.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.Reflection;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
using System.Net.Http;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
@ -113,7 +115,7 @@ namespace Org.OpenAPITools.Client
public Configuration() public Configuration()
{ {
Proxy = null; 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"; BasePath = "http://petstore.swagger.io:80/v2";
DefaultHeaders = new ConcurrentDictionary<string, string>(); DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>(); ApiKey = new ConcurrentDictionary<string, string>();
@ -361,6 +363,30 @@ namespace Org.OpenAPITools.Client
/// <value>The access token.</value> /// <value>The access token.</value>
public virtual string AccessToken { get; set; } 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> /// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server. /// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary> /// </summary>
@ -684,6 +710,10 @@ namespace Org.OpenAPITools.Client
Username = second.Username ?? first.Username, Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password, Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken, 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, HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat,

View File

@ -12,6 +12,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client
/// <value>Access token.</value> /// <value>Access token.</value>
string AccessToken { get; } 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> /// <summary>
/// Gets the API key. /// Gets the API key.
/// </summary> /// </summary>

View File

@ -21,7 +21,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="CompareNETObjects" Version="4.61.0" /> <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="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Polly" Version="7.2.3" /> <PackageReference Include="Polly" Version="7.2.3" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" /> <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/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.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/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs src/Org.OpenAPITools/Client/ExceptionFactory.cs

View File

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

View File

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

View File

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

View File

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

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net; using System.Net;
using System.Net.Mime; using System.Net.Mime;
using Org.OpenAPITools.Client; using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api namespace Org.OpenAPITools.Api
@ -674,9 +675,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -769,9 +780,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -844,9 +865,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -921,9 +952,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1015,9 +1056,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1111,9 +1162,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1207,9 +1268,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1305,9 +1376,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1542,9 +1623,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1637,9 +1728,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1719,9 +1820,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1803,9 +1914,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1887,9 +2008,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1973,9 +2104,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -2061,9 +2202,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -2151,9 +2302,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request

View File

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

View File

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

View File

@ -25,18 +25,18 @@ using System.Threading.Tasks;
using System.Web; using System.Web;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp; using RestSharp;
using RestSharp.Deserializers; using RestSharp.Serializers;
using RestSharpMethod = RestSharp.Method; using RestSharpMethod = RestSharp.Method;
using Polly; using Polly;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
/// <summary> /// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary> /// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer
{ {
private readonly IReadableConfiguration _configuration; private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json"; 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)); var result = (T)Deserialize(response, typeof(T));
return result; return result;
@ -94,7 +96,7 @@ namespace Org.OpenAPITools.Client
/// <param name="response">The HTTP response.</param> /// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param> /// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns> /// <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 if (type == typeof(byte[])) // return byte array
{ {
@ -147,15 +149,22 @@ namespace Org.OpenAPITools.Client
} }
} }
public string RootElement { get; set; } public ISerializer Serializer => this;
public string Namespace { get; set; } public IDeserializer Deserializer => this;
public string DateFormat { get; set; }
public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept;
public SupportsContentType SupportsContentType => contentType =>
contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) ||
contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase);
public string ContentType public string ContentType
{ {
get { return _contentType; } get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); } set { throw new InvalidOperationException("Not allowed to set content type."); }
} }
public DataFormat DataFormat => DataFormat.Json;
} }
/// <summary> /// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), /// 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. /// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary> /// </summary>
/// <param name="request">The RestSharp request object</param> /// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request); partial void InterceptRequest(RestRequest request);
/// <summary> /// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code. /// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary> /// </summary>
/// <param name="request">The RestSharp request object</param> /// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response 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> /// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url. /// 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) switch (method)
{ {
case HttpMethod.Get: case HttpMethod.Get:
other = RestSharpMethod.GET; other = RestSharpMethod.Get;
break; break;
case HttpMethod.Post: case HttpMethod.Post:
other = RestSharpMethod.POST; other = RestSharpMethod.Post;
break; break;
case HttpMethod.Put: case HttpMethod.Put:
other = RestSharpMethod.PUT; other = RestSharpMethod.Put;
break; break;
case HttpMethod.Delete: case HttpMethod.Delete:
other = RestSharpMethod.DELETE; other = RestSharpMethod.Delete;
break; break;
case HttpMethod.Head: case HttpMethod.Head:
other = RestSharpMethod.HEAD; other = RestSharpMethod.Head;
break; break;
case HttpMethod.Options: case HttpMethod.Options:
other = RestSharpMethod.OPTIONS; other = RestSharpMethod.Options;
break; break;
case HttpMethod.Patch: case HttpMethod.Patch:
other = RestSharpMethod.PATCH; other = RestSharpMethod.Patch;
break; break;
default: default:
throw new ArgumentOutOfRangeException("method", method, null); throw new ArgumentOutOfRangeException("method", method, null);
@ -277,11 +286,7 @@ namespace Org.OpenAPITools.Client
if (options == null) throw new ArgumentNullException("options"); if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration"); if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method)) RestRequest request = new RestRequest(path, Method(method));
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
if (options.PathParameters != null) if (options.PathParameters != null)
{ {
@ -376,25 +381,17 @@ namespace Org.OpenAPITools.Client
var bytes = ClientUtils.ReadAsBytes(file); var bytes = ClientUtils.ReadAsBytes(file);
var fileStream = file as FileStream; var fileStream = file as FileStream;
if (fileStream != null) 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 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; return request;
} }
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response) private ApiResponse<T> ToApiResponse<T>(RestResponse<T> response)
{ {
T result = response.Data; T result = response.Data;
string rawContent = response.Content; 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) if (response.Cookies != null)
{ {
foreach (var responseCookies in response.Cookies) foreach (var responseCookies in response.Cookies.Cast<Cookie>())
{ {
transformed.Cookies.Add( transformed.Cookies.Add(
new Cookie( new Cookie(
@ -433,54 +438,46 @@ namespace Org.OpenAPITools.Client
private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration) private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration)
{ {
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers(); var cookies = new CookieContainer();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null) if (options.Cookies != null && options.Cookies.Count > 0)
{ {
client.AddHandler("application/json", () => existingDeserializer); foreach (var cookie in options.Cookies)
client.AddHandler("text/json", () => existingDeserializer); {
client.AddHandler("text/x-json", () => existingDeserializer); cookies.Add(new Cookie(cookie.Name, cookie.Value));
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);
} }
var xmlDeserializer = new XmlDeserializer(); var clientOptions = new RestClientOptions(baseUrl)
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; ClientCertificates = configuration.ClientCertificates,
} CookieContainer = cookies,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
if (configuration.UserAgent != null) RestClient client = new RestClient(clientOptions)
{ .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
client.UserAgent = configuration.UserAgent;
}
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); InterceptRequest(req);
IRestResponse<T> response; RestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null) if (RetryConfiguration.RetryPolicy != null)
{ {
var policy = RetryConfiguration.RetryPolicy; var policy = RetryConfiguration.RetryPolicy;
@ -528,7 +525,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0) if (response.Cookies != null && response.Cookies.Count > 0)
{ {
if (result.Cookies == null) result.Cookies = new List<Cookie>(); 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( var cookie = new Cookie(
restResponseCookie.Name, 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)) 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; var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers(); var clientOptions = new RestClientOptions(baseUrl)
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
{ {
client.AddHandler("application/json", () => existingDeserializer); ClientCertificates = configuration.ClientCertificates,
client.AddHandler("text/json", () => existingDeserializer); MaxTimeout = configuration.Timeout,
client.AddHandler("text/x-json", () => existingDeserializer); Proxy = configuration.Proxy,
client.AddHandler("text/javascript", () => existingDeserializer); UserAgent = configuration.UserAgent
client.AddHandler("*+json", () => existingDeserializer); };
}
else 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 = client.UseAuthenticator(new OAuthAuthenticator(
client.AddHandler("application/json", () => customDeserializer); configuration.OAuthTokenUrl,
client.AddHandler("text/json", () => customDeserializer); configuration.OAuthClientId,
client.AddHandler("text/x-json", () => customDeserializer); configuration.OAuthClientSecret,
client.AddHandler("text/javascript", () => customDeserializer); configuration.OAuthFlow,
client.AddHandler("*+json", () => customDeserializer); SerializerSettings,
} configuration));
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;
} }
InterceptRequest(req); InterceptRequest(req);
IRestResponse<T> response; RestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null) if (RetryConfiguration.AsyncRetryPolicy != null)
{ {
var policy = RetryConfiguration.AsyncRetryPolicy; var policy = RetryConfiguration.AsyncRetryPolicy;
@ -645,7 +623,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0) if (response.Cookies != null && response.Cookies.Count > 0)
{ {
if (result.Cookies == null) result.Cookies = new List<Cookie>(); 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( var cookie = new Cookie(
restResponseCookie.Name, 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.Reflection;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
using System.Net.Http;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
@ -118,7 +120,7 @@ namespace Org.OpenAPITools.Client
public Configuration() public Configuration()
{ {
Proxy = null; 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"; BasePath = "http://petstore.swagger.io:80/v2";
DefaultHeaders = new ConcurrentDictionary<string, string>(); DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>(); ApiKey = new ConcurrentDictionary<string, string>();
@ -366,6 +368,30 @@ namespace Org.OpenAPITools.Client
/// <value>The access token.</value> /// <value>The access token.</value>
public virtual string AccessToken { get; set; } 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> /// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server. /// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary> /// </summary>
@ -689,6 +715,10 @@ namespace Org.OpenAPITools.Client
Username = second.Username ?? first.Username, Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password, Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken, 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, HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat,

View File

@ -12,6 +12,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client
/// <value>Access token.</value> /// <value>Access token.</value>
string AccessToken { get; } 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> /// <summary>
/// Gets the API key. /// Gets the API key.
/// </summary> /// </summary>

View File

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

View File

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

View File

@ -21,9 +21,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="CompareNETObjects" Version="4.61.0" /> <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="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="Polly" Version="7.2.3" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" /> <PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup> </ItemGroup>

View File

@ -98,6 +98,9 @@ src/Org.OpenAPITools/Api/UserApi.cs
src/Org.OpenAPITools/Client/ApiClient.cs src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.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/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs src/Org.OpenAPITools/Client/ExceptionFactory.cs

View File

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

View File

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

View File

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

View File

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

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net; using System.Net;
using System.Net.Mime; using System.Net.Mime;
using Org.OpenAPITools.Client; using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api namespace Org.OpenAPITools.Api
@ -674,9 +675,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -769,9 +780,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -844,9 +865,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -921,9 +952,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1015,9 +1056,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1111,9 +1162,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1207,9 +1268,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1305,9 +1376,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1542,9 +1623,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1637,9 +1728,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1719,9 +1820,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1803,9 +1914,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1887,9 +2008,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1973,9 +2104,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -2061,9 +2202,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -2151,9 +2302,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request

View File

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

View File

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

View File

@ -25,18 +25,18 @@ using System.Threading.Tasks;
using System.Web; using System.Web;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp; using RestSharp;
using RestSharp.Deserializers; using RestSharp.Serializers;
using RestSharpMethod = RestSharp.Method; using RestSharpMethod = RestSharp.Method;
using Polly; using Polly;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
/// <summary> /// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary> /// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer
{ {
private readonly IReadableConfiguration _configuration; private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json"; 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)); var result = (T)Deserialize(response, typeof(T));
return result; return result;
@ -94,7 +96,7 @@ namespace Org.OpenAPITools.Client
/// <param name="response">The HTTP response.</param> /// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param> /// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns> /// <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 if (type == typeof(byte[])) // return byte array
{ {
@ -147,15 +149,22 @@ namespace Org.OpenAPITools.Client
} }
} }
public string RootElement { get; set; } public ISerializer Serializer => this;
public string Namespace { get; set; } public IDeserializer Deserializer => this;
public string DateFormat { get; set; }
public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept;
public SupportsContentType SupportsContentType => contentType =>
contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) ||
contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase);
public string ContentType public string ContentType
{ {
get { return _contentType; } get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); } set { throw new InvalidOperationException("Not allowed to set content type."); }
} }
public DataFormat DataFormat => DataFormat.Json;
} }
/// <summary> /// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), /// 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. /// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary> /// </summary>
/// <param name="request">The RestSharp request object</param> /// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request); partial void InterceptRequest(RestRequest request);
/// <summary> /// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code. /// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary> /// </summary>
/// <param name="request">The RestSharp request object</param> /// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response 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> /// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url. /// 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) switch (method)
{ {
case HttpMethod.Get: case HttpMethod.Get:
other = RestSharpMethod.GET; other = RestSharpMethod.Get;
break; break;
case HttpMethod.Post: case HttpMethod.Post:
other = RestSharpMethod.POST; other = RestSharpMethod.Post;
break; break;
case HttpMethod.Put: case HttpMethod.Put:
other = RestSharpMethod.PUT; other = RestSharpMethod.Put;
break; break;
case HttpMethod.Delete: case HttpMethod.Delete:
other = RestSharpMethod.DELETE; other = RestSharpMethod.Delete;
break; break;
case HttpMethod.Head: case HttpMethod.Head:
other = RestSharpMethod.HEAD; other = RestSharpMethod.Head;
break; break;
case HttpMethod.Options: case HttpMethod.Options:
other = RestSharpMethod.OPTIONS; other = RestSharpMethod.Options;
break; break;
case HttpMethod.Patch: case HttpMethod.Patch:
other = RestSharpMethod.PATCH; other = RestSharpMethod.Patch;
break; break;
default: default:
throw new ArgumentOutOfRangeException("method", method, null); throw new ArgumentOutOfRangeException("method", method, null);
@ -277,11 +286,7 @@ namespace Org.OpenAPITools.Client
if (options == null) throw new ArgumentNullException("options"); if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration"); if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method)) RestRequest request = new RestRequest(path, Method(method));
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
if (options.PathParameters != null) if (options.PathParameters != null)
{ {
@ -376,25 +381,17 @@ namespace Org.OpenAPITools.Client
var bytes = ClientUtils.ReadAsBytes(file); var bytes = ClientUtils.ReadAsBytes(file);
var fileStream = file as FileStream; var fileStream = file as FileStream;
if (fileStream != null) 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 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; return request;
} }
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response) private ApiResponse<T> ToApiResponse<T>(RestResponse<T> response)
{ {
T result = response.Data; T result = response.Data;
string rawContent = response.Content; 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) if (response.Cookies != null)
{ {
foreach (var responseCookies in response.Cookies) foreach (var responseCookies in response.Cookies.Cast<Cookie>())
{ {
transformed.Cookies.Add( transformed.Cookies.Add(
new Cookie( new Cookie(
@ -433,54 +438,46 @@ namespace Org.OpenAPITools.Client
private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration) private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration)
{ {
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers(); var cookies = new CookieContainer();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null) if (options.Cookies != null && options.Cookies.Count > 0)
{ {
client.AddHandler("application/json", () => existingDeserializer); foreach (var cookie in options.Cookies)
client.AddHandler("text/json", () => existingDeserializer); {
client.AddHandler("text/x-json", () => existingDeserializer); cookies.Add(new Cookie(cookie.Name, cookie.Value));
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);
} }
var xmlDeserializer = new XmlDeserializer(); var clientOptions = new RestClientOptions(baseUrl)
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; ClientCertificates = configuration.ClientCertificates,
} CookieContainer = cookies,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
if (configuration.UserAgent != null) RestClient client = new RestClient(clientOptions)
{ .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
client.UserAgent = configuration.UserAgent;
}
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); InterceptRequest(req);
IRestResponse<T> response; RestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null) if (RetryConfiguration.RetryPolicy != null)
{ {
var policy = RetryConfiguration.RetryPolicy; var policy = RetryConfiguration.RetryPolicy;
@ -528,7 +525,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0) if (response.Cookies != null && response.Cookies.Count > 0)
{ {
if (result.Cookies == null) result.Cookies = new List<Cookie>(); 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( var cookie = new Cookie(
restResponseCookie.Name, 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)) 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; var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers(); var clientOptions = new RestClientOptions(baseUrl)
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
{ {
client.AddHandler("application/json", () => existingDeserializer); ClientCertificates = configuration.ClientCertificates,
client.AddHandler("text/json", () => existingDeserializer); MaxTimeout = configuration.Timeout,
client.AddHandler("text/x-json", () => existingDeserializer); Proxy = configuration.Proxy,
client.AddHandler("text/javascript", () => existingDeserializer); UserAgent = configuration.UserAgent
client.AddHandler("*+json", () => existingDeserializer); };
}
else 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 = client.UseAuthenticator(new OAuthAuthenticator(
client.AddHandler("application/json", () => customDeserializer); configuration.OAuthTokenUrl,
client.AddHandler("text/json", () => customDeserializer); configuration.OAuthClientId,
client.AddHandler("text/x-json", () => customDeserializer); configuration.OAuthClientSecret,
client.AddHandler("text/javascript", () => customDeserializer); configuration.OAuthFlow,
client.AddHandler("*+json", () => customDeserializer); SerializerSettings,
} configuration));
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;
} }
InterceptRequest(req); InterceptRequest(req);
IRestResponse<T> response; RestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null) if (RetryConfiguration.AsyncRetryPolicy != null)
{ {
var policy = RetryConfiguration.AsyncRetryPolicy; var policy = RetryConfiguration.AsyncRetryPolicy;
@ -645,7 +623,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0) if (response.Cookies != null && response.Cookies.Count > 0)
{ {
if (result.Cookies == null) result.Cookies = new List<Cookie>(); 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( var cookie = new Cookie(
restResponseCookie.Name, 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.Reflection;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
using System.Net.Http;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
@ -118,7 +120,7 @@ namespace Org.OpenAPITools.Client
public Configuration() public Configuration()
{ {
Proxy = null; 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"; BasePath = "http://petstore.swagger.io:80/v2";
DefaultHeaders = new ConcurrentDictionary<string, string>(); DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>(); ApiKey = new ConcurrentDictionary<string, string>();
@ -366,6 +368,30 @@ namespace Org.OpenAPITools.Client
/// <value>The access token.</value> /// <value>The access token.</value>
public virtual string AccessToken { get; set; } 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> /// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server. /// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary> /// </summary>
@ -689,6 +715,10 @@ namespace Org.OpenAPITools.Client
Username = second.Username ?? first.Username, Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password, Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken, 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, HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat,

View File

@ -12,6 +12,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client
/// <value>Access token.</value> /// <value>Access token.</value>
string AccessToken { get; } 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> /// <summary>
/// Gets the API key. /// Gets the API key.
/// </summary> /// </summary>

View File

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

View File

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

View File

@ -21,9 +21,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="CompareNETObjects" Version="4.61.0" /> <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="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="Polly" Version="7.2.3" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" /> <PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup> </ItemGroup>

View File

@ -97,6 +97,9 @@ src/Org.OpenAPITools/Api/UserApi.cs
src/Org.OpenAPITools/Client/ApiClient.cs src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.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/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs src/Org.OpenAPITools/Client/ExceptionFactory.cs

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net; using System.Net;
using System.Net.Mime; using System.Net.Mime;
using Org.OpenAPITools.Client; using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api namespace Org.OpenAPITools.Api
@ -674,9 +675,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -769,9 +780,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -844,9 +865,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -921,9 +952,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1015,9 +1056,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1111,9 +1162,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1207,9 +1268,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1305,9 +1376,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1542,9 +1623,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1637,9 +1728,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1719,9 +1820,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1803,9 +1914,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1887,9 +2008,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1973,9 +2104,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -2061,9 +2202,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -2151,9 +2302,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request

View File

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

View File

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

View File

@ -24,18 +24,18 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp; using RestSharp;
using RestSharp.Deserializers; using RestSharp.Serializers;
using RestSharpMethod = RestSharp.Method; using RestSharpMethod = RestSharp.Method;
using Polly; using Polly;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
/// <summary> /// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary> /// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer
{ {
private readonly IReadableConfiguration _configuration; private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json"; 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)); var result = (T)Deserialize(response, typeof(T));
return result; return result;
@ -93,7 +95,7 @@ namespace Org.OpenAPITools.Client
/// <param name="response">The HTTP response.</param> /// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param> /// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns> /// <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 if (type == typeof(byte[])) // return byte array
{ {
@ -146,15 +148,22 @@ namespace Org.OpenAPITools.Client
} }
} }
public string RootElement { get; set; } public ISerializer Serializer => this;
public string Namespace { get; set; } public IDeserializer Deserializer => this;
public string DateFormat { get; set; }
public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept;
public SupportsContentType SupportsContentType => contentType =>
contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) ||
contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase);
public string ContentType public string ContentType
{ {
get { return _contentType; } get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); } set { throw new InvalidOperationException("Not allowed to set content type."); }
} }
public DataFormat DataFormat => DataFormat.Json;
} }
/// <summary> /// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), /// 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. /// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary> /// </summary>
/// <param name="request">The RestSharp request object</param> /// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request); partial void InterceptRequest(RestRequest request);
/// <summary> /// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code. /// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary> /// </summary>
/// <param name="request">The RestSharp request object</param> /// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response 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> /// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url. /// 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) switch (method)
{ {
case HttpMethod.Get: case HttpMethod.Get:
other = RestSharpMethod.GET; other = RestSharpMethod.Get;
break; break;
case HttpMethod.Post: case HttpMethod.Post:
other = RestSharpMethod.POST; other = RestSharpMethod.Post;
break; break;
case HttpMethod.Put: case HttpMethod.Put:
other = RestSharpMethod.PUT; other = RestSharpMethod.Put;
break; break;
case HttpMethod.Delete: case HttpMethod.Delete:
other = RestSharpMethod.DELETE; other = RestSharpMethod.Delete;
break; break;
case HttpMethod.Head: case HttpMethod.Head:
other = RestSharpMethod.HEAD; other = RestSharpMethod.Head;
break; break;
case HttpMethod.Options: case HttpMethod.Options:
other = RestSharpMethod.OPTIONS; other = RestSharpMethod.Options;
break; break;
case HttpMethod.Patch: case HttpMethod.Patch:
other = RestSharpMethod.PATCH; other = RestSharpMethod.Patch;
break; break;
default: default:
throw new ArgumentOutOfRangeException("method", method, null); throw new ArgumentOutOfRangeException("method", method, null);
@ -276,11 +285,7 @@ namespace Org.OpenAPITools.Client
if (options == null) throw new ArgumentNullException("options"); if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration"); if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method)) RestRequest request = new RestRequest(path, Method(method));
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
if (options.PathParameters != null) if (options.PathParameters != null)
{ {
@ -375,25 +380,17 @@ namespace Org.OpenAPITools.Client
var bytes = ClientUtils.ReadAsBytes(file); var bytes = ClientUtils.ReadAsBytes(file);
var fileStream = file as FileStream; var fileStream = file as FileStream;
if (fileStream != null) 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 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; return request;
} }
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response) private ApiResponse<T> ToApiResponse<T>(RestResponse<T> response)
{ {
T result = response.Data; T result = response.Data;
string rawContent = response.Content; 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) if (response.Cookies != null)
{ {
foreach (var responseCookies in response.Cookies) foreach (var responseCookies in response.Cookies.Cast<Cookie>())
{ {
transformed.Cookies.Add( transformed.Cookies.Add(
new Cookie( new Cookie(
@ -432,54 +437,46 @@ namespace Org.OpenAPITools.Client
private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration) private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration)
{ {
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers(); var cookies = new CookieContainer();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null) if (options.Cookies != null && options.Cookies.Count > 0)
{ {
client.AddHandler("application/json", () => existingDeserializer); foreach (var cookie in options.Cookies)
client.AddHandler("text/json", () => existingDeserializer); {
client.AddHandler("text/x-json", () => existingDeserializer); cookies.Add(new Cookie(cookie.Name, cookie.Value));
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);
} }
var xmlDeserializer = new XmlDeserializer(); var clientOptions = new RestClientOptions(baseUrl)
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; ClientCertificates = configuration.ClientCertificates,
} CookieContainer = cookies,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent
};
if (configuration.UserAgent != null) RestClient client = new RestClient(clientOptions)
{ .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration));
client.UserAgent = configuration.UserAgent;
}
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); InterceptRequest(req);
IRestResponse<T> response; RestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null) if (RetryConfiguration.RetryPolicy != null)
{ {
var policy = RetryConfiguration.RetryPolicy; var policy = RetryConfiguration.RetryPolicy;
@ -527,7 +524,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0) if (response.Cookies != null && response.Cookies.Count > 0)
{ {
if (result.Cookies == null) result.Cookies = new List<Cookie>(); 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( var cookie = new Cookie(
restResponseCookie.Name, 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)) 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; var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers(); var clientOptions = new RestClientOptions(baseUrl)
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
{ {
client.AddHandler("application/json", () => existingDeserializer); ClientCertificates = configuration.ClientCertificates,
client.AddHandler("text/json", () => existingDeserializer); MaxTimeout = configuration.Timeout,
client.AddHandler("text/x-json", () => existingDeserializer); Proxy = configuration.Proxy,
client.AddHandler("text/javascript", () => existingDeserializer); UserAgent = configuration.UserAgent
client.AddHandler("*+json", () => existingDeserializer); };
}
else 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 = client.UseAuthenticator(new OAuthAuthenticator(
client.AddHandler("application/json", () => customDeserializer); configuration.OAuthTokenUrl,
client.AddHandler("text/json", () => customDeserializer); configuration.OAuthClientId,
client.AddHandler("text/x-json", () => customDeserializer); configuration.OAuthClientSecret,
client.AddHandler("text/javascript", () => customDeserializer); configuration.OAuthFlow,
client.AddHandler("*+json", () => customDeserializer); SerializerSettings,
} configuration));
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;
} }
InterceptRequest(req); InterceptRequest(req);
IRestResponse<T> response; RestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null) if (RetryConfiguration.AsyncRetryPolicy != null)
{ {
var policy = RetryConfiguration.AsyncRetryPolicy; var policy = RetryConfiguration.AsyncRetryPolicy;
@ -644,7 +622,7 @@ namespace Org.OpenAPITools.Client
if (response.Cookies != null && response.Cookies.Count > 0) if (response.Cookies != null && response.Cookies.Count > 0)
{ {
if (result.Cookies == null) result.Cookies = new List<Cookie>(); 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( var cookie = new Cookie(
restResponseCookie.Name, 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.Reflection;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
using System.Net.Http;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
@ -113,7 +115,7 @@ namespace Org.OpenAPITools.Client
public Configuration() public Configuration()
{ {
Proxy = null; 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"; BasePath = "http://petstore.swagger.io:80/v2";
DefaultHeaders = new ConcurrentDictionary<string, string>(); DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>(); ApiKey = new ConcurrentDictionary<string, string>();
@ -361,6 +363,30 @@ namespace Org.OpenAPITools.Client
/// <value>The access token.</value> /// <value>The access token.</value>
public virtual string AccessToken { get; set; } 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> /// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server. /// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary> /// </summary>
@ -684,6 +710,10 @@ namespace Org.OpenAPITools.Client
Username = second.Username ?? first.Username, Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password, Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken, 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, HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat,

View File

@ -12,6 +12,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using Org.OpenAPITools.Client.Auth;
namespace Org.OpenAPITools.Client namespace Org.OpenAPITools.Client
{ {
@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client
/// <value>Access token.</value> /// <value>Access token.</value>
string AccessToken { get; } 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> /// <summary>
/// Gets the API key. /// Gets the API key.
/// </summary> /// </summary>

View File

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

View File

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

View File

@ -21,9 +21,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="CompareNETObjects" Version="4.61.0" /> <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="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="Polly" Version="7.2.3" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" /> <PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup> </ItemGroup>

View File

@ -97,6 +97,9 @@ src/Org.OpenAPITools/Api/UserApi.cs
src/Org.OpenAPITools/Client/ApiClient.cs src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.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/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs src/Org.OpenAPITools/Client/ExceptionFactory.cs

View File

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

View File

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

View File

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

View File

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

View File

@ -15,6 +15,7 @@ using System.Linq;
using System.Net; using System.Net;
using System.Net.Mime; using System.Net.Mime;
using Org.OpenAPITools.Client; using Org.OpenAPITools.Client;
using Org.OpenAPITools.Client.Auth;
using Org.OpenAPITools.Model; using Org.OpenAPITools.Model;
namespace Org.OpenAPITools.Api namespace Org.OpenAPITools.Api
@ -674,9 +675,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -769,9 +780,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -844,9 +865,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -921,9 +952,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1015,9 +1056,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1111,9 +1162,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1207,9 +1268,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1305,9 +1376,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1542,9 +1623,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1637,9 +1728,19 @@ namespace Org.OpenAPITools.Api
} }
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1719,9 +1820,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1803,9 +1914,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1887,9 +2008,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -1973,9 +2104,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -2061,9 +2202,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request
@ -2151,9 +2302,19 @@ namespace Org.OpenAPITools.Api
// authentication (petstore_auth) required // authentication (petstore_auth) required
// oauth required // oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{ {
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); 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 // make the HTTP request

View File

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

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