add Identity based Http Provider ...
This commit is contained in:
@@ -12,6 +12,7 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using IdentityModel.AspNetCore.OAuth2Introspection;
|
||||
using xHttpService.Interfaces;
|
||||
|
||||
namespace xIdentityService.DI
|
||||
{
|
||||
@@ -29,6 +30,22 @@ namespace xIdentityService.DI
|
||||
return xIdentityServiceConfigSection.Get<XIdentityServiceConfiguration>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register Identity Based Support Http Service ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
public static void AddXIdentityHttpService(
|
||||
this IServiceCollection source
|
||||
)
|
||||
{
|
||||
//
|
||||
var httpProvider = source.GetRegisteredService<IXHttpProvider>();
|
||||
if (!httpProvider.IsNull())
|
||||
{
|
||||
source.AddScoped<IXIdentityHttpProvider, XIdentityHttpProvider>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register Service and All it's Requirements
|
||||
/// </summary>
|
||||
@@ -207,6 +224,10 @@ namespace xIdentityService.DI
|
||||
// Register Person Service ...
|
||||
services.AddXPersonService(lifeTime);
|
||||
|
||||
//
|
||||
// Register Identity Based Http Provider ...
|
||||
services.AddXIdentityHttpService();
|
||||
|
||||
//
|
||||
// Try To Register InMemoryTokenProvier if it's not Provided ...
|
||||
IXTokenProvider xTokenProvider = null;
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
using RestSharp;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using xHttpService.Constants;
|
||||
using xIdentityService.Models;
|
||||
using xHttpService.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xIdentityService.Interfaces
|
||||
{
|
||||
public partial interface IXIdentityHttpProvider : IXHttpProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Get an Instance of RestRequest ...
|
||||
/// </summary>
|
||||
/// <param name="endpoint"></param>
|
||||
/// <param name="addXPoweredValue"></param>
|
||||
/// <param name="params"></param>
|
||||
/// <param name="headers"></param>
|
||||
/// <param name="queryStrings"></param>
|
||||
/// <returns></returns>
|
||||
RestRequest GetRestRequest(
|
||||
string endpoint,
|
||||
bool addXPoweredValue = true,
|
||||
IDictionary<string, string> @params = null,
|
||||
IDictionary<string, string> headers = null,
|
||||
IDictionary<string, string> queryStrings = null
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Handle Call Specific Request and retrieve Response
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="method"></param>
|
||||
/// <param name="supportRefreshingTokens"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
Task<T> RunRestRequest<T>(
|
||||
RestClient client,
|
||||
RestRequest request,
|
||||
XHttpMethod method,
|
||||
bool supportRefreshingTokens = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XBaseRestResponse<T>> RunRestRequestByResponse<T>(
|
||||
RestClient client,
|
||||
RestRequest request,
|
||||
XHttpMethod method,
|
||||
bool supportRefreshingTokens = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
using RestSharp;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using xCommons.Providers;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xHttpService.Constants;
|
||||
using xHttpService.Providers;
|
||||
using xIdentityModels.Models;
|
||||
using xIdentityService.Models;
|
||||
using xIdentityService.Constants;
|
||||
using xIdentityModels.Extensions;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityService.Interfaces;
|
||||
using xHttpService.Configurations;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using xIdentityService.Configuration;
|
||||
|
||||
namespace xIdentityService.Providers
|
||||
{
|
||||
public partial class XIdentityHttpProvider : XHttpProvider, IXIdentityHttpProvider
|
||||
{
|
||||
private readonly IXTokenProvider tokenProvider;
|
||||
private readonly IXIdentityProvider identityProvider;
|
||||
private readonly ILogger<XIdentityHttpProvider> logger;
|
||||
private readonly XValidationProvider validationProvider;
|
||||
private readonly XIdentityServiceConfiguration identityConfiguration;
|
||||
|
||||
public XIdentityHttpProvider(
|
||||
IXTokenProvider tokenProvider,
|
||||
IXIdentityProvider identityProvider,
|
||||
ILogger<XIdentityHttpProvider> logger,
|
||||
XValidationProvider validationProvider,
|
||||
XHttpServiceConfiguration configuration,
|
||||
XIdentityServiceConfiguration identityConfiguration
|
||||
) : base(
|
||||
logger,
|
||||
configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
this.logger = logger;
|
||||
this.tokenProvider = tokenProvider;
|
||||
this.identityProvider = identityProvider;
|
||||
this.validationProvider = validationProvider;
|
||||
this.identityConfiguration = identityConfiguration;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get an Instance of RestRequest ...
|
||||
/// </summary>
|
||||
/// <param name="endpoint"></param>
|
||||
/// <param name="addXPoweredValue"></param>
|
||||
/// <param name="params"></param>
|
||||
/// <param name="headers"></param>
|
||||
/// <param name="queryStrings"></param>
|
||||
/// <returns></returns>
|
||||
public RestRequest GetRestRequest(
|
||||
string endpoint,
|
||||
bool addXPoweredValue = true,
|
||||
IDictionary<string, string> @params = null,
|
||||
IDictionary<string, string> headers = null,
|
||||
IDictionary<string, string> queryStrings = null
|
||||
)
|
||||
{
|
||||
//
|
||||
var url = endpoint;
|
||||
|
||||
//
|
||||
// Add Route Payloads ...
|
||||
if (!@params.IsNull() && @params.Count > 0)
|
||||
{
|
||||
//
|
||||
var enumerator = @params.GetEnumerator();
|
||||
while (enumerator.MoveNext())
|
||||
{
|
||||
//
|
||||
var item = enumerator.Current;
|
||||
|
||||
//
|
||||
url = url.Replace(item.Key, item.Value.ToUrlEncoded());
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Add Query Strings ...
|
||||
if (!queryStrings.IsNull() && queryStrings.Count > 0)
|
||||
{
|
||||
//
|
||||
url = $"{url}?";
|
||||
var enumerator = queryStrings.GetEnumerator();
|
||||
while (enumerator.MoveNext())
|
||||
{
|
||||
//
|
||||
var item = enumerator.Current;
|
||||
|
||||
//
|
||||
url += $"{item.Key}={item.Value.ToUrlEncoded()}&";
|
||||
}
|
||||
|
||||
//
|
||||
// remove lates & ...
|
||||
if (url.EndsWith("&"))
|
||||
{
|
||||
url = url.Substring(0, url.Length - 1);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Create request ...
|
||||
var request = new RestRequest(url, DataFormat.Json);
|
||||
|
||||
//
|
||||
if (addXPoweredValue)
|
||||
{
|
||||
request.AddHeader(XAuthorization.XPoweredBy, identityConfiguration.XPoweredValue);
|
||||
}
|
||||
|
||||
//
|
||||
// Add Headers to request ...
|
||||
if (!headers.IsNull() && headers.Count > 0)
|
||||
{
|
||||
//
|
||||
var enumerator = headers.GetEnumerator();
|
||||
while (enumerator.MoveNext())
|
||||
{
|
||||
//
|
||||
var item = enumerator.Current;
|
||||
request.AddHeader(item.Key, item.Value);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
return request;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle Call Specific Request and retrieve Response
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="method"></param>
|
||||
/// <param name="supportRefreshingTokens"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public async Task<T> RunRestRequest<T>(
|
||||
RestClient client,
|
||||
RestRequest request,
|
||||
XHttpMethod method,
|
||||
bool supportRefreshingTokens = true,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var response = await Task.Run(async () =>
|
||||
{
|
||||
//
|
||||
IRestResponse resp = null;
|
||||
|
||||
//
|
||||
// Call Endpoint Service using Specified Method ...
|
||||
switch (method)
|
||||
{
|
||||
//
|
||||
// Get ...
|
||||
case XHttpMethod.GET:
|
||||
resp = client.Get(request);
|
||||
break;
|
||||
|
||||
//
|
||||
// Put ...
|
||||
case XHttpMethod.PUT:
|
||||
resp = client.Put(request);
|
||||
break;
|
||||
|
||||
//
|
||||
// Post ...
|
||||
case XHttpMethod.POST:
|
||||
resp = client.Post(request);
|
||||
break;
|
||||
|
||||
//
|
||||
// Delete ...
|
||||
case XHttpMethod.DELETE:
|
||||
resp = client.Delete(request);
|
||||
break;
|
||||
}
|
||||
|
||||
//
|
||||
if (!resp.IsSuccessful)
|
||||
{
|
||||
//
|
||||
// Log Exception ...
|
||||
logger.LogError($"Error: {resp.ErrorMessage}");
|
||||
logger.LogError($"Exception: {resp.ErrorException.ToJSON()}");
|
||||
if (!resp.ErrorMessage.IsNullOrEmpty() &&
|
||||
resp.ErrorMessage.Contains("timed out"))
|
||||
{
|
||||
XException.Timeout.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Refresh Tokens or Issue Correct Exception ...
|
||||
if (supportRefreshingTokens &&
|
||||
resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||
{
|
||||
//
|
||||
var isRefreshed = request.Parameters.Any(rp =>
|
||||
rp.Name == XParam.XIsRefreshed.GetStringValue() &&
|
||||
rp.Value.ToString().ToNormalString() == true.ToJSON());
|
||||
|
||||
//
|
||||
logger.LogInformation($"isRefreshed: {isRefreshed}");
|
||||
|
||||
//
|
||||
// Get Access Token ...
|
||||
XTokenResponse tokens = null;
|
||||
var accessToken = request.Parameters.FirstOrDefault(rp =>
|
||||
rp.Name.ToNormalString() == XAuthorization.Header.ToNormalString()).Value.ToString();
|
||||
if (!accessToken.IsNullOrEmpty())
|
||||
{
|
||||
//
|
||||
accessToken = accessToken.Replace(XAuthorization.TokenIdentifier, "");
|
||||
|
||||
//
|
||||
if (!accessToken.IsNullOrEmpty())
|
||||
{
|
||||
tokens = await tokenProvider.RetrieveToken(accessToken);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Refresh Token and then re do request ...
|
||||
if (!isRefreshed &&
|
||||
!accessToken.IsNullOrEmpty() &&
|
||||
!tokens.IsNull() &&
|
||||
tokens.IsRefreshable())
|
||||
{
|
||||
//
|
||||
request.AddHeader(XParam.XIsRefreshed.GetStringValue(), true.ToJSON());
|
||||
|
||||
//
|
||||
// Refreshe Tokens ...
|
||||
var refreshedTokens = await identityProvider.RefreshTokens(tokens);
|
||||
|
||||
//
|
||||
// Renew Rest Client with Refreshed Tokens ...
|
||||
var timeout = client.Timeout;
|
||||
client = GetRestClient(
|
||||
tokens: refreshedTokens,
|
||||
baseUrl: client.BaseUrl.ToString()
|
||||
);
|
||||
client.Timeout = Timeout.Infinite;
|
||||
|
||||
//
|
||||
// Do Request Again using renew Client ...
|
||||
return await RunRestRequest<T>(
|
||||
client: client,
|
||||
request: request,
|
||||
method: method);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
var ex = resp.Content.ToXError();
|
||||
if (!ex.IsNull())
|
||||
{
|
||||
throw ex.ToException();
|
||||
}
|
||||
|
||||
//
|
||||
// UnAuthorized ...
|
||||
if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||
{
|
||||
XException.NotAuthorized.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// NotFound ...
|
||||
if (resp.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
{
|
||||
XException.NotFound.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
XException.ActionFailed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var result = resp.Content.FromJSON<T>();
|
||||
return result;
|
||||
}, cancellationToken);
|
||||
|
||||
//
|
||||
return response;
|
||||
}
|
||||
public async Task<XBaseRestResponse<T>> RunRestRequestByResponse<T>(
|
||||
RestClient client,
|
||||
RestRequest request,
|
||||
XHttpMethod method,
|
||||
bool supportRefreshingTokens = true,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var response = await Task.Run(async () =>
|
||||
{
|
||||
//
|
||||
IRestResponse resp = null;
|
||||
|
||||
//
|
||||
// Call Endpoint Service using Specified Method ...
|
||||
switch (method)
|
||||
{
|
||||
//
|
||||
// Get ...
|
||||
case XHttpMethod.GET:
|
||||
resp = client.Get(request);
|
||||
break;
|
||||
|
||||
//
|
||||
// Put ...
|
||||
case XHttpMethod.PUT:
|
||||
resp = client.Put(request);
|
||||
break;
|
||||
|
||||
//
|
||||
// Post ...
|
||||
case XHttpMethod.POST:
|
||||
resp = client.Post(request);
|
||||
break;
|
||||
|
||||
//
|
||||
// Delete ...
|
||||
case XHttpMethod.DELETE:
|
||||
resp = client.Delete(request);
|
||||
break;
|
||||
}
|
||||
|
||||
//
|
||||
if (!resp.IsSuccessful)
|
||||
{
|
||||
//
|
||||
// Log Exception ...
|
||||
logger.LogError($"Error: {resp.ErrorMessage}");
|
||||
logger.LogError($"Exception: {resp.ErrorException.ToJSON()}");
|
||||
if (!resp.ErrorMessage.IsNullOrEmpty() &&
|
||||
resp.ErrorMessage.Contains("timed out"))
|
||||
{
|
||||
XException.Timeout.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Refresh Tokens or Issue Correct Exception ...
|
||||
if (supportRefreshingTokens &&
|
||||
resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||
{
|
||||
//
|
||||
var isRefreshed = request.Parameters.Any(rp =>
|
||||
rp.Name == XParam.XIsRefreshed.GetStringValue() &&
|
||||
rp.Value.ToString().ToNormalString() == true.ToJSON());
|
||||
|
||||
//
|
||||
logger.LogInformation($"isRefreshed: {isRefreshed}");
|
||||
|
||||
//
|
||||
// Get Access Token ...
|
||||
XTokenResponse tokens = null;
|
||||
var accessToken = request.Parameters.FirstOrDefault(rp =>
|
||||
rp.Name.ToNormalString() == XAuthorization.Header.ToNormalString()).Value.ToString();
|
||||
if (!accessToken.IsNullOrEmpty())
|
||||
{
|
||||
//
|
||||
accessToken = accessToken.Replace(XAuthorization.TokenIdentifier, "");
|
||||
|
||||
//
|
||||
if (!accessToken.IsNullOrEmpty())
|
||||
{
|
||||
tokens = await tokenProvider.RetrieveToken(accessToken);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Refresh Token and then re do request ...
|
||||
if (!isRefreshed &&
|
||||
!accessToken.IsNullOrEmpty() &&
|
||||
!tokens.IsNull() &&
|
||||
tokens.IsRefreshable())
|
||||
{
|
||||
//
|
||||
request.AddHeader(XParam.XIsRefreshed.GetStringValue(), true.ToJSON());
|
||||
|
||||
//
|
||||
// Refreshe Tokens ...
|
||||
var refreshedTokens = await identityProvider.RefreshTokens(tokens);
|
||||
|
||||
//
|
||||
// Renew Rest Client with Refreshed Tokens ...
|
||||
var timeout = client.Timeout;
|
||||
client = GetRestClient(
|
||||
tokens: refreshedTokens,
|
||||
baseUrl: client.BaseUrl.ToString()
|
||||
);
|
||||
client.Timeout = Timeout.Infinite;
|
||||
|
||||
//
|
||||
// Do Request Again using renew Client ...
|
||||
return await RunRestRequestByResponse<T>(
|
||||
client: client,
|
||||
request: request,
|
||||
method: method
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
var ex = resp.Content.ToXError();
|
||||
if (!ex.IsNull())
|
||||
{
|
||||
throw ex.ToException();
|
||||
}
|
||||
|
||||
//
|
||||
// UnAuthorized ...
|
||||
if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||
{
|
||||
XException.NotAuthorized.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// NotFound ...
|
||||
if (resp.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
{
|
||||
XException.NotFound.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
XException.ActionFailed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var result = new XBaseRestResponse<T>
|
||||
{
|
||||
Response = resp,
|
||||
Model = resp.Content.FromJSON<T>()
|
||||
};
|
||||
|
||||
//
|
||||
return result;
|
||||
}, cancellationToken);
|
||||
|
||||
//
|
||||
return response;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,8 +32,6 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../xDataService/xDataService.csproj" />
|
||||
<ProjectReference Include="../xHttpService/xHttpService.csproj" />
|
||||
<!-- <PackageReference Include="xDashboard.xDataService" Version="1.0.0" /> -->
|
||||
<!-- <PackageReference Include="xDashboard.xHttpService" Version="1.0.0" /> -->
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Dependencies -->
|
||||
|
||||
Reference in New Issue
Block a user