From e9001a7735f5a3e1ecdd2452f13fd3830a6e0c88 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Sat, 17 Oct 2026 17:15:41 +0330 Subject: [PATCH] last ... --- Extensions/HttpContextExtensions.cs | 116 ++++++++++----- Extensions/XRequestExtensions.cs | 4 +- Interfaces/IXIdentityProvider.cs | 13 ++ Middlewares/XApiKeyUsageMiddleware.cs | 112 ++++++++++++++ Middlewares/XProxyMiddleware.cs | 8 +- Partial/XIdentityProvider+Open.cs | 204 +++++++++++++++++++++++++- 6 files changed, 414 insertions(+), 43 deletions(-) create mode 100644 Middlewares/XApiKeyUsageMiddleware.cs diff --git a/Extensions/HttpContextExtensions.cs b/Extensions/HttpContextExtensions.cs index fa5d594..5548c79 100644 --- a/Extensions/HttpContextExtensions.cs +++ b/Extensions/HttpContextExtensions.cs @@ -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 + { /// /// Retrieve Authentication Service ... /// /// /// - public static IAuthenticationService GetAuthenticationService (this HttpContext context) { + public static IAuthenticationService GetAuthenticationService(this HttpContext context) + { // var result = context.RequestServices - .GetRequiredService (); + .GetRequiredService(); // return result; @@ -30,34 +33,37 @@ namespace xIdentityService.Extensions { /// /// /// - public static async Task GetXTokenAsync ( + public static async Task 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 /// /// - public static async Task GetAccessToken (this HttpContext context) { + public static async Task 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 /// /// - public static async Task GetRefreshToken (this HttpContext context) { + public static async Task 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 /// /// - public static async Task GetTokenExpiresAt (this HttpContext context) { + public static async Task 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 (); + var expiresAt = expiresAtStr.ConvertTo(); // return expiresAt; @@ -128,18 +141,49 @@ namespace xIdentityService.Extensions { /// Retrieve All Required Tokens /// /// - public static async Task RetrieveTokensAsXTokenResponse (HttpContext context) { + public static async Task 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 }; } + + /// + /// Retrieve Request Path ... + /// + /// + /// + public static string GetRequestPath(this HttpContext source) + { + // + var result = source.GetRequestPath(); + return result; + } + + /// + /// Retrieve Request Path ... + /// + /// + /// + 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; + } } } \ No newline at end of file diff --git a/Extensions/XRequestExtensions.cs b/Extensions/XRequestExtensions.cs index a73070b..edb1b1c 100644 --- a/Extensions/XRequestExtensions.cs +++ b/Extensions/XRequestExtensions.cs @@ -11,7 +11,7 @@ namespace xIdentityService.Extensions /// /// /// - 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 /// /// /// - public static string ExtractClientIP(HttpRequest source) + public static string ExtractClientIP(this HttpRequest source) { // var result = source?.HttpContext.Connection.RemoteIpAddress?.ToString(); diff --git a/Interfaces/IXIdentityProvider.cs b/Interfaces/IXIdentityProvider.cs index 1296728..cd5e709 100644 --- a/Interfaces/IXIdentityProvider.cs +++ b/Interfaces/IXIdentityProvider.cs @@ -321,6 +321,19 @@ namespace xIdentityService.Interfaces XOpenActionInnerDto model ); + // + Task GetApiKey( + XDeviceDto device, + string apiKey + ); + Task GetApiKey( + XOpenActionInnerDto dto + ); + Task GetApiKey( + string token, + string request + ); + // Task GetUserInfo( XDeviceDto device, diff --git a/Middlewares/XApiKeyUsageMiddleware.cs b/Middlewares/XApiKeyUsageMiddleware.cs new file mode 100644 index 0000000..726d6bd --- /dev/null +++ b/Middlewares/XApiKeyUsageMiddleware.cs @@ -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(); + var endpoint = + endpointFeature.IsNull() + ? null + : endpointFeature.Endpoint; + var apiKeyAccessAttibute = + endpoint.IsNull() + ? null + : endpoint.Metadata.GetMetadata(); + 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 + { + /// + /// Adding XProxy Middleware to Applications ... + /// + /// + public static void UseXApiKeyUsage(this IApplicationBuilder app) + { + app.UseMiddleware(); + } + } +} diff --git a/Middlewares/XProxyMiddleware.cs b/Middlewares/XProxyMiddleware.cs index 273b195..b82888c 100644 --- a/Middlewares/XProxyMiddleware.cs +++ b/Middlewares/XProxyMiddleware.cs @@ -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 ... /// /// - /// + /// /// private async Task ProcessResponseContent ( HttpContext context, diff --git a/Partial/XIdentityProvider+Open.cs b/Partial/XIdentityProvider+Open.cs index 4926fa4..e2a8e93 100644 --- a/Partial/XIdentityProvider+Open.cs +++ b/Partial/XIdentityProvider+Open.cs @@ -20,7 +20,7 @@ namespace xIdentityService.Providers /// Prepare API Based Device to Open Actions ... /// /// - public XDeviceDto GetDevice() + public XDeviceDto GetDevice() { // var os = "XSaherElmOS"; @@ -171,6 +171,208 @@ namespace xIdentityService.Providers } #endregion + // + #region GetApiKey ... + public async Task 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 GetApiKey( + XOpenActionInnerDto dto + ) + { + // + return await GetApiKey( + token: dto.Token, + request: dto.Payload + ); + } + + public async Task 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(); + 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 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 UseApiKey( + XOpenActionInnerDto dto + ) + { + // + return await UseApiKey( + token: dto.Token, + request: dto.Payload + ); + } + + public async Task 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(); + if (requestModel.IsNull()) + { + XException.ActionFailed.Throw(); + } + + // + var resultJson = SecurityProvider.Decrypt(requestModel.Payload); + var result = resultJson.FromJSON(); + if (result.IsNull()) + { + XException.NotFound.Throw(); + } + + // + return result; + } + #endregion + // #region GetUserInfo ... public async Task GetUserInfo(