last ...
This commit is contained in:
@@ -7,17 +7,20 @@ using xIdentityService.Constants;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace xIdentityService.Extensions {
|
||||
public static class HttpContextExtensions {
|
||||
namespace xIdentityService.Extensions
|
||||
{
|
||||
public static class HttpContextExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieve Authentication Service ...
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <returns></returns>
|
||||
public static IAuthenticationService GetAuthenticationService (this HttpContext context) {
|
||||
public static IAuthenticationService GetAuthenticationService(this HttpContext context)
|
||||
{
|
||||
//
|
||||
var result = context.RequestServices
|
||||
.GetRequiredService<IAuthenticationService> ();
|
||||
.GetRequiredService<IAuthenticationService>();
|
||||
|
||||
//
|
||||
return result;
|
||||
@@ -30,34 +33,37 @@ namespace xIdentityService.Extensions {
|
||||
/// <param name="tokenName"></param>
|
||||
/// <param name="scheme"></param>
|
||||
/// <returns></returns>
|
||||
public static async Task<string> GetXTokenAsync (
|
||||
public static async Task<string> GetXTokenAsync(
|
||||
this HttpContext context,
|
||||
string tokenName,
|
||||
XAuthenticationScheme scheme = XAuthenticationScheme.XToken
|
||||
) {
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate Args ...
|
||||
if (tokenName.IsNullOrEmpty ()) {
|
||||
if (tokenName.IsNullOrEmpty())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
var authService = context.GetAuthenticationService ();
|
||||
if (authService.IsNull ()) {
|
||||
var authService = context.GetAuthenticationService();
|
||||
if (authService.IsNull())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
var authResult = await authService
|
||||
.AuthenticateAsync (
|
||||
.AuthenticateAsync(
|
||||
context,
|
||||
scheme
|
||||
.GetStringValue ()
|
||||
.GetStringValue()
|
||||
);
|
||||
|
||||
//
|
||||
var result = authResult?.Properties?
|
||||
.GetTokenValue (tokenName);
|
||||
.GetTokenValue(tokenName);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -65,22 +71,25 @@ namespace xIdentityService.Extensions {
|
||||
/// Retrieve Access Token
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static async Task<string> GetAccessToken (this HttpContext context) {
|
||||
public static async Task<string> GetAccessToken(this HttpContext context)
|
||||
{
|
||||
//
|
||||
var accessToken = context.Request.Headers[XAuthorization.Header]
|
||||
.ToString ();
|
||||
if (accessToken.IsNullOrEmpty ()) {
|
||||
.ToString();
|
||||
if (accessToken.IsNullOrEmpty())
|
||||
{
|
||||
accessToken = await context
|
||||
.GetTokenAsync (XAuthorization.AccessToken);
|
||||
.GetTokenAsync(XAuthorization.AccessToken);
|
||||
}
|
||||
|
||||
//
|
||||
if (accessToken
|
||||
.ToNormalString ()
|
||||
.Contains (XAuthorization.TokenIdentifier
|
||||
.ToNormalString ())) {
|
||||
.ToNormalString()
|
||||
.Contains(XAuthorization.TokenIdentifier
|
||||
.ToNormalString()))
|
||||
{
|
||||
accessToken = accessToken
|
||||
.Remove (0, XAuthorization.TokenIdentifier.Length);
|
||||
.Remove(0, XAuthorization.TokenIdentifier.Length);
|
||||
}
|
||||
|
||||
//
|
||||
@@ -91,13 +100,15 @@ namespace xIdentityService.Extensions {
|
||||
/// Retrieve Refresh Token
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static async Task<string> GetRefreshToken (this HttpContext context) {
|
||||
public static async Task<string> GetRefreshToken(this HttpContext context)
|
||||
{
|
||||
//
|
||||
var refreshToken = context.Request.Headers[XAuthorization.RefreshToken]
|
||||
.ToString ();
|
||||
if (refreshToken.IsNullOrEmpty ()) {
|
||||
.ToString();
|
||||
if (refreshToken.IsNullOrEmpty())
|
||||
{
|
||||
refreshToken = await context
|
||||
.GetTokenAsync (XAuthorization.RefreshToken);
|
||||
.GetTokenAsync(XAuthorization.RefreshToken);
|
||||
}
|
||||
|
||||
//
|
||||
@@ -108,17 +119,19 @@ namespace xIdentityService.Extensions {
|
||||
/// Retrieve Access Token Expiration Date
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static async Task<long> GetTokenExpiresAt (this HttpContext context) {
|
||||
public static async Task<long> GetTokenExpiresAt(this HttpContext context)
|
||||
{
|
||||
//
|
||||
var expiresAtStr = context.Request.Headers[XAuthorization.ExpiresAt]
|
||||
.ToString ();
|
||||
if (expiresAtStr.IsNullOrEmpty ()) {
|
||||
.ToString();
|
||||
if (expiresAtStr.IsNullOrEmpty())
|
||||
{
|
||||
expiresAtStr = await context
|
||||
.GetTokenAsync (XAuthorization.ExpiresAt);
|
||||
.GetTokenAsync(XAuthorization.ExpiresAt);
|
||||
}
|
||||
|
||||
//
|
||||
var expiresAt = expiresAtStr.ConvertTo<long> ();
|
||||
var expiresAt = expiresAtStr.ConvertTo<long>();
|
||||
|
||||
//
|
||||
return expiresAt;
|
||||
@@ -128,18 +141,49 @@ namespace xIdentityService.Extensions {
|
||||
/// Retrieve All Required Tokens
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static async Task<XTokenResponse> RetrieveTokensAsXTokenResponse (HttpContext context) {
|
||||
public static async Task<XTokenResponse> RetrieveTokensAsXTokenResponse(HttpContext context)
|
||||
{
|
||||
//
|
||||
var accessToken = await GetAccessToken (context);
|
||||
var refreshToken = await GetRefreshToken (context);
|
||||
var expiresAt = await GetTokenExpiresAt (context);
|
||||
var accessToken = await GetAccessToken(context);
|
||||
var refreshToken = await GetRefreshToken(context);
|
||||
var expiresAt = await GetTokenExpiresAt(context);
|
||||
|
||||
//
|
||||
return new XTokenResponse {
|
||||
return new XTokenResponse
|
||||
{
|
||||
AccessToken = accessToken,
|
||||
RefreshToken = refreshToken,
|
||||
ExpiresAt = expiresAt
|
||||
RefreshToken = refreshToken,
|
||||
ExpiresAt = expiresAt
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve Request Path ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetRequestPath(this HttpContext source)
|
||||
{
|
||||
//
|
||||
var result = source.GetRequestPath();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve Request Path ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetRequestPath(this HttpRequest source)
|
||||
{
|
||||
//
|
||||
var path = source.Path;
|
||||
var pathBase = source.PathBase;
|
||||
var query = source.QueryString;
|
||||
|
||||
//
|
||||
var result = $"{pathBase}{path}{query}";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ namespace xIdentityService.Extensions
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static string ExtractApiKey(HttpRequest source)
|
||||
public static string ExtractApiKey(this HttpRequest source)
|
||||
{
|
||||
//
|
||||
var key = XHeader.ApiKey.GetStringValue();
|
||||
@@ -24,7 +24,7 @@ namespace xIdentityService.Extensions
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static string ExtractClientIP(HttpRequest source)
|
||||
public static string ExtractClientIP(this HttpRequest source)
|
||||
{
|
||||
//
|
||||
var result = source?.HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
|
||||
@@ -321,6 +321,19 @@ namespace xIdentityService.Interfaces
|
||||
XOpenActionInnerDto model
|
||||
);
|
||||
|
||||
//
|
||||
Task<Guid> GetApiKey(
|
||||
XDeviceDto device,
|
||||
string apiKey
|
||||
);
|
||||
Task<Guid> GetApiKey(
|
||||
XOpenActionInnerDto dto
|
||||
);
|
||||
Task<Guid> GetApiKey(
|
||||
string token,
|
||||
string request
|
||||
);
|
||||
|
||||
//
|
||||
Task<XOpenActionUserInfoDto> GetUserInfo(
|
||||
XDeviceDto device,
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using xCommons.Extensions;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using xIdentityService.Attributes;
|
||||
using xIdentityService.Interfaces;
|
||||
using xIdentityService.Extensions;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using xIdentityModels.Dtos;
|
||||
|
||||
namespace xIdentityService.Middlewares
|
||||
{
|
||||
public class XApiKeyUsageMiddleware
|
||||
{
|
||||
//
|
||||
#region Properties ...
|
||||
private readonly RequestDelegate next;
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Constructor ...
|
||||
public XApiKeyUsageMiddleware(
|
||||
RequestDelegate next
|
||||
)
|
||||
{
|
||||
this.next = next;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
//
|
||||
#region Actions ...
|
||||
public async Task InvokeAsync(
|
||||
HttpContext context,
|
||||
IXIdentityProvider identityProvider
|
||||
)
|
||||
{
|
||||
//
|
||||
// Check Context Has ApiKey Authorization Filter ...
|
||||
var endpointFeature = context.Features.Get<IEndpointFeature>();
|
||||
var endpoint =
|
||||
endpointFeature.IsNull()
|
||||
? null
|
||||
: endpointFeature.Endpoint;
|
||||
var apiKeyAccessAttibute =
|
||||
endpoint.IsNull()
|
||||
? null
|
||||
: endpoint.Metadata.GetMetadata<XApiKeyAccessAttribute>();
|
||||
if (!apiKeyAccessAttibute.IsNull())
|
||||
{
|
||||
//
|
||||
var sw = Stopwatch.StartNew();
|
||||
var requestedOn = DateTime.UtcNow;
|
||||
var httpMethod = context.Request.Method;
|
||||
var statusCode = StatusCodes.Status200OK;
|
||||
var endpointName = context.GetRequestPath();
|
||||
var clientIp = context.Request.ExtractClientIP();
|
||||
|
||||
//
|
||||
var device = identityProvider.GetDevice();
|
||||
var apiKey = context.Request.ExtractApiKey();
|
||||
var apiKeyId = await identityProvider.GetApiKey(
|
||||
device: device,
|
||||
apiKey: apiKey
|
||||
);
|
||||
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
statusCode = context.Response.StatusCode;
|
||||
}
|
||||
catch
|
||||
{
|
||||
statusCode = StatusCodes.Status500InternalServerError;
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
//
|
||||
sw.Stop();
|
||||
var dto = new XApiKeyUsageDto
|
||||
{
|
||||
ApiKeyId = apiKeyId,
|
||||
ClientIP = clientIp,
|
||||
Endpoint = endpointName,
|
||||
StatusCode = statusCode,
|
||||
HttpMethod = httpMethod,
|
||||
RequestedOn = requestedOn,
|
||||
ResponseTimeMs = sw.ElapsedMilliseconds,
|
||||
};
|
||||
await identityProvider.AddApiKeyUsage();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
public static class XApiKeyUsageMiddlewareDIExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adding XProxy Middleware to Applications ...
|
||||
/// </summary>
|
||||
/// <param name="app"></param>
|
||||
public static void UseXApiKeyUsage(this IApplicationBuilder app)
|
||||
{
|
||||
app.UseMiddleware<XApiKeyUsageMiddleware>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,12 +42,12 @@ namespace xIdentityService.Middlewares {
|
||||
IHttpClientFactory httpClientFactory
|
||||
) : base (loggerFactory) {
|
||||
//
|
||||
this.CONFIGURATION = configuration;
|
||||
this.NEXT_MIDDLEWARE = nextMiddleware;
|
||||
CONFIGURATION = configuration;
|
||||
NEXT_MIDDLEWARE = nextMiddleware;
|
||||
|
||||
//
|
||||
// Create Http Client ...
|
||||
this.HTTP_CLIENT = httpClientFactory
|
||||
HTTP_CLIENT = httpClientFactory
|
||||
.CreateClient (XProxyConstants.XPROXY_HTTP_CLIENT);
|
||||
|
||||
//
|
||||
@@ -547,7 +547,7 @@ namespace xIdentityService.Middlewares {
|
||||
/// Processing Response Content and Handle it on HttpContextResponse ...
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <param name="response"></param>
|
||||
/// <param name="message"></param>
|
||||
/// <returns></returns>
|
||||
private async Task ProcessResponseContent (
|
||||
HttpContext context,
|
||||
|
||||
@@ -20,7 +20,7 @@ namespace xIdentityService.Providers
|
||||
/// Prepare API Based Device to Open Actions ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public XDeviceDto GetDevice()
|
||||
public XDeviceDto GetDevice()
|
||||
{
|
||||
//
|
||||
var os = "XSaherElmOS";
|
||||
@@ -171,6 +171,208 @@ namespace xIdentityService.Providers
|
||||
}
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region GetApiKey ...
|
||||
public async Task<Guid> GetApiKey(
|
||||
XDeviceDto device,
|
||||
string apiKey
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate Args ...
|
||||
validationProvider.NotNull(device);
|
||||
validationProvider.NotEmpty(apiKey);
|
||||
|
||||
//
|
||||
// Prepare Open Action Model ...
|
||||
var opaModel = new XOpenActionRequestDto
|
||||
{
|
||||
Device = device,
|
||||
Payload = apiKey,
|
||||
Action = XOpenActions.GetApiKey,
|
||||
Timestamp = DateTime.UtcNow.AddMinutes(5).ToTimestamp().ToString()
|
||||
};
|
||||
if (!opaModel.Validate())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Fill Checksum Filed ...
|
||||
var token = opaModel.ToOpenActionToken();
|
||||
opaModel.Checksum = token;
|
||||
|
||||
//
|
||||
// Prepare Request ...
|
||||
var opaJson = opaModel.ToJson();
|
||||
var requestString = SecurityProvider.Encrypt(opaJson);
|
||||
|
||||
//
|
||||
return await GetApiKey(
|
||||
token: token,
|
||||
request: requestString
|
||||
);
|
||||
}
|
||||
|
||||
public async Task<Guid> GetApiKey(
|
||||
XOpenActionInnerDto dto
|
||||
)
|
||||
{
|
||||
//
|
||||
return await GetApiKey(
|
||||
token: dto.Token,
|
||||
request: dto.Payload
|
||||
);
|
||||
}
|
||||
|
||||
public async Task<Guid> GetApiKey(
|
||||
string token,
|
||||
string request
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate Args ...
|
||||
validationProvider.NotEmpty(token);
|
||||
validationProvider.NotEmpty(request);
|
||||
|
||||
//
|
||||
// Retrieve and Validate Response ...
|
||||
var response = await OpenGet(
|
||||
token: token,
|
||||
actionRequest: request
|
||||
);
|
||||
if (response.IsNull() ||
|
||||
response.Token.IsNullOrEmpty() ||
|
||||
response.Payload.IsNullOrEmpty()
|
||||
)
|
||||
{
|
||||
XException.ActionFailed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Now we Have to Converts Repose Payload to Result Model ...
|
||||
// Note that the respose Model's payload here is Decrypted and
|
||||
// actually is Json Representation of Result Model ...
|
||||
var requestModel = response.Payload.FromJSON<XOpenActionRequestDto>();
|
||||
if (requestModel.IsNull())
|
||||
{
|
||||
XException.ActionFailed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var resultString = SecurityProvider.Decrypt(requestModel.Payload);
|
||||
var result = new Guid(resultString);
|
||||
if (result.IsNull())
|
||||
{
|
||||
XException.NotFound.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region UseApiKey ...
|
||||
public async Task<bool> UseApiKey(
|
||||
XDeviceDto device,
|
||||
XApiKeyUsageDto apiKeyUsage
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate Args ...
|
||||
validationProvider.NotNull(device);
|
||||
validationProvider.NotNull(apiKeyUsage);
|
||||
|
||||
//
|
||||
// Prepare Open Action Model ...
|
||||
var opaModel = new XOpenActionRequestDto
|
||||
{
|
||||
Device = device,
|
||||
Payload = apiKeyUsage.ToJSON(),
|
||||
Action = XOpenActions.UseApiKey,
|
||||
Timestamp = DateTime.UtcNow.AddMinutes(5).ToTimestamp().ToString()
|
||||
};
|
||||
if (!opaModel.Validate())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Fill Checksum Filed ...
|
||||
var token = opaModel.ToOpenActionToken();
|
||||
opaModel.Checksum = token;
|
||||
|
||||
//
|
||||
// Prepare Request ...
|
||||
var opaJson = opaModel.ToJson();
|
||||
var requestString = SecurityProvider.Encrypt(opaJson);
|
||||
|
||||
//
|
||||
return await UseApiKey(
|
||||
token: token,
|
||||
request: requestString
|
||||
);
|
||||
}
|
||||
|
||||
public async Task<bool> UseApiKey(
|
||||
XOpenActionInnerDto dto
|
||||
)
|
||||
{
|
||||
//
|
||||
return await UseApiKey(
|
||||
token: dto.Token,
|
||||
request: dto.Payload
|
||||
);
|
||||
}
|
||||
|
||||
public async Task<bool> UseApiKey(
|
||||
string token,
|
||||
string request
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate Args ...
|
||||
validationProvider.NotEmpty(token);
|
||||
validationProvider.NotEmpty(request);
|
||||
|
||||
//
|
||||
// Retrieve and Validate Response ...
|
||||
var response = await OpenGet(
|
||||
token: token,
|
||||
actionRequest: request
|
||||
);
|
||||
if (response.IsNull() ||
|
||||
response.Token.IsNullOrEmpty() ||
|
||||
response.Payload.IsNullOrEmpty()
|
||||
)
|
||||
{
|
||||
XException.ActionFailed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Now we Have to Converts Repose Payload to Result Model ...
|
||||
// Note that the respose Model's payload here is Decrypted and
|
||||
// actually is Json Representation of Result Model ...
|
||||
var requestModel = response.Payload.FromJSON<XOpenActionRequestDto>();
|
||||
if (requestModel.IsNull())
|
||||
{
|
||||
XException.ActionFailed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var resultJson = SecurityProvider.Decrypt(requestModel.Payload);
|
||||
var result = resultJson.FromJSON<bool>();
|
||||
if (result.IsNull())
|
||||
{
|
||||
XException.NotFound.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region GetUserInfo ...
|
||||
public async Task<XOpenActionUserInfoDto> GetUserInfo(
|
||||
|
||||
Reference in New Issue
Block a user