diff --git a/Attributes/XApiKeyAccessAttribute.cs b/Attributes/XApiKeyAccessAttribute.cs new file mode 100644 index 0000000..f3f16e5 --- /dev/null +++ b/Attributes/XApiKeyAccessAttribute.cs @@ -0,0 +1,201 @@ +using System; +using IdentityModel; +using System.Threading; +using xCommons.Constants; +using xCommons.Extensions; +using xExceptions.Constants; +using xIdentityModels.Models; +using System.Security.Claims; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using xIdentityModels.Constants; +using System.Collections.Generic; +using xIdentityService.Constants; +using xIdentityService.Interfaces; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.Extensions.DependencyInjection; + +namespace xIdentityService.Attributes +{ + [AttributeUsage( + AttributeTargets.Class | AttributeTargets.Method, + AllowMultiple = false, + Inherited = true + )] + public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter + { + /// + /// Optional allowed scopes. If empty, no scope enforcement. + /// + public XApiKeyScope[] Scopes { get; set; } + + public XApiKeyAccessAttribute( + XApiKeyScope[] scopes = null + ) + { + // + if (!scopes.HasChild()) + { + scopes = [XApiKeyScope.Read]; + } + + // + Scopes = scopes; + } + + /// + /// Authorization Filtering ... + /// + /// + public void OnAuthorization(AuthorizationFilterContext context) + { + Task.FromResult(OnAuthorizationAsync(context)); + } + + /// + /// Handle Authorization Filtering Using Tasks ... + /// + /// + /// + /// + private async Task OnAuthorizationAsync( + AuthorizationFilterContext context, + CancellationToken cancellationToken = default + ) + { + // + // Access HttpContext ... + var http = context.HttpContext; + var error = XException.NotAuthorized.ToXError(); + var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue(); + + // + try + { + // + // Obtain the endpoint currently being executed + var endpointFeature = http.Features.Get(); + var endpoint = endpointFeature?.Endpoint; + if (endpoint.IsNull() || + endpointFeature.IsNull() + ) + { + // + error.Message = "Endpoint not Accessible ..."; + context.Result = new UnauthorizedObjectResult(error); + return; + } + + // + // Retrieve Identity Provider Service from DI ... + var identityService = http.RequestServices + .GetService(); + if (identityService.IsNull()) + { + // + error.Message = "Api Key Service not Registered ..."; + context.Result = new UnauthorizedObjectResult(error); + return; + } + + // + // Checking Header ... + var apiKeyHeader = XHeader.ApiKey.GetStringValue(); + if (!http.Request.Headers.ContainsKey(apiKeyHeader)) + { + // + error.Message = "ApiKey not Exists ..."; + context.Result = new UnauthorizedObjectResult(error); + return; + } + + // + // Extract ApiKey from Header ... + var apiKey = http.Request.Headers[apiKeyHeader].ToString(); + if (apiKey.IsNullOrEmpty()) + { + // + error.Message = "ApiKey not Provided ..."; + context.Result = new UnauthorizedObjectResult(error); + return; + } + + // + // Extract Client IP ... + var clientIP = http.Request.HttpContext.Connection.RemoteIpAddress?.ToString(); + var scopes = + !Scopes.HasChild() + ? string.Empty + : Scopes.ToListString(); + + // + // Prepare Validation Request ... + var validationRequest = new XApiKeyValidationRequest + { + ApiKey = apiKey, + ClientIP = clientIP, + RequiredScope = scopes + }; + + // + // Validating ApiKey ... + var validationResponse = identityService.ValidateApiKey( + request: validationRequest, + cancellationToken: cancellationToken + ) + .GetAwaiter() + .GetResult(); + if (validationResponse.Errors.HasChild()) + { + // + var message = validationResponse.Errors.ToListString(','); + error.Message = message; + context.Result = new UnauthorizedObjectResult(error); + return; + } + + // + // Creating Claims ... + var claims = new List { + // + // Owner Identifier of API Key ... + new(ClaimTypes.Name, validationResponse.OwnerId), + new(JwtClaimTypes.Subject, validationResponse.OwnerId), + // + // Application Id ... + new(XCustomClaims.ApplicationId, validationResponse.ApplicationId.ToString()), + // + // Authentication Type ... + new(XCustomClaims.AuthType, apiKeyAuthentication), + }; + + // + // Add Scopes ... + if (validationResponse.Scopes != null) + { + // + foreach (var scope in validationResponse.Scopes) + { + claims.Add(new Claim(JwtClaimTypes.Scope, scope)); + } + } + + // + // Create Principal and Ticket ... + var identity = new ClaimsIdentity(claims, apiKeyAuthentication); + var principal = new ClaimsPrincipal(identity); + + // + http.User = principal; + } + catch + { + // + error.Message = "ApiKey authorization failed ..."; + context.Result = new UnauthorizedObjectResult(error); + } + } + } +} \ No newline at end of file diff --git a/Constants/XApiAccountEndpoint.cs b/Constants/XApiAccountEndpoint.cs index f5914d1..0b6520d 100644 --- a/Constants/XApiAccountEndpoint.cs +++ b/Constants/XApiAccountEndpoint.cs @@ -221,7 +221,7 @@ namespace xIdentityService.Constants [StringValue("Applications")] CreateApplication, - [StringValue("Applications")] + [StringValue("Applications/{id}")] UpdateApplication, [StringValue("Applications/{id}")] diff --git a/Controllers/XBaseTestIdentityController.cs b/Controllers/XBaseTestIdentityController.cs new file mode 100644 index 0000000..9c05c4f --- /dev/null +++ b/Controllers/XBaseTestIdentityController.cs @@ -0,0 +1,111 @@ +using xCommons.Providers; +using xCommons.Attributes; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using xIdentityModels.Constants; +using xIdentityService.Interfaces; +using xIdentityService.Attributes; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; + +namespace xIdentityService.Controllers +{ + public abstract class XBaseTestIdentityController : XBaseIdentityController + { + protected XBaseTestIdentityController( + ILogger logger, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base(logger, appConfiguration, identityProvider, validationProvider) + { } + + // + #region ApiKey Actions ... + /// + /// a simple Hello for Accessing ApiKey Authorization ... + /// + /// + [XApiKeyAccess] + [AllowAnonymous] + [RequireXPowered] + [HttpGet("HiApiKeyAccess")] + public ActionResult HiApiKeyAccess() + { + // + var result = $"Hi ApiKey Access, is Passed ..."; + + // + return Ok(result); + } + + /// + /// a simple Hello for Accessing ApiKey Read Access ... + /// + /// + [AllowAnonymous] + [RequireXPowered] + [HttpGet("HiApiKeyReadAccess")] + [XApiKeyAccess(Scopes = [XApiKeyScope.Read])] + public ActionResult HiApiKeyReadAccess() + { + // + var result = $"Hi ApiKey Read Access, is Passed ..."; + + // + return Ok(result); + } + + /// + /// a simple Hello for Accessing ApiKey Write Access ... + /// + /// + [AllowAnonymous] + [RequireXPowered] + [HttpGet("HiApiKeyWriteAccess")] + [XApiKeyAccess(scopes: [XApiKeyScope.Write])] + public ActionResult HiApiKeyWriteAccess() + { + // + var result = $"Hi ApiKey Write Access, is Passed ..."; + + // + return Ok(result); + } + + /// + /// a simple Hello for Accessing ApiKey Manage Access ... + /// + /// + [AllowAnonymous] + [RequireXPowered] + [HttpGet("HiApiKeyManageAccess")] + [XApiKeyAccess(scopes: [XApiKeyScope.Manage])] + public ActionResult HiApiKManageAccess() + { + // + var result = $"Hi ApiKey Manage Access, is Passed ..."; + + // + return Ok(result); + } + + /// + /// a simple Hello for Accessing ApiKey Admin Access ... + /// + /// + [AllowAnonymous] + [RequireXPowered] + [HttpGet("HiApiKeyAdminAccess")] + [XApiKeyAccess(scopes: [XApiKeyScope.Admin])] + public ActionResult HiApiKeyAdminAccess() + { + // + var result = $"Hi ApiKey Admin Access, is Passed ..."; + + // + return Ok(result); + } + #endregion + } +} \ No newline at end of file diff --git a/Interfaces/IXIdentityProvider.cs b/Interfaces/IXIdentityProvider.cs index da4ff26..1296728 100644 --- a/Interfaces/IXIdentityProvider.cs +++ b/Interfaces/IXIdentityProvider.cs @@ -369,11 +369,13 @@ namespace xIdentityService.Interfaces /// Update Specified Application ... /// /// + /// /// /// /// Task UpdateApplication( XTokenResponse tokens, + int id, XApplicationDto item, CancellationToken cancellationToken = default ); @@ -461,11 +463,13 @@ namespace xIdentityService.Interfaces /// Update Specified ApiKey ... /// /// + /// /// /// /// Task UpdateApiKey( XTokenResponse tokens, + Guid id, XApiKeyDto item, CancellationToken cancellationToken = default ); @@ -540,11 +544,13 @@ namespace xIdentityService.Interfaces /// Update Specified Api Key Usage ... /// /// + /// /// /// /// Task UpdateApiKeyUsage( XTokenResponse tokens, + long id, XApiKeyUsageDto item, CancellationToken cancellationToken = default ); diff --git a/Partial/XIdentityProvider+Application.cs b/Partial/XIdentityProvider+Application.cs index e62c35c..1a3d27e 100644 --- a/Partial/XIdentityProvider+Application.cs +++ b/Partial/XIdentityProvider+Application.cs @@ -7,16 +7,14 @@ using xExceptions.Constants; using System.Threading.Tasks; using xIdentityModels.Models; using xHttpService.Constants; +using xHttpService.Extensions; using System.Collections.Generic; using xIdentityService.Constants; -using xHttpService.Extensions; -using MongoDB.Bson; namespace xIdentityService.Providers { public partial class XIdentityProvider { - // #region Applications ... // @@ -65,11 +63,13 @@ namespace xIdentityService.Providers /// Update Specified Application ... /// /// + /// /// /// /// public async Task UpdateApplication( XTokenResponse tokens, + int id, XApplicationDto item, CancellationToken cancellationToken = default ) @@ -84,12 +84,21 @@ namespace xIdentityService.Providers tokens.AccessToken ) .ValidateGroupAsync(); + if (!id.IsValidIntId()) + { + XException.InvalidArgs.Throw(); + } // var client = GetRestClient(tokens); // - var request = GetRestRequet(XApiAccountEndpoint.UpdateApplication); + var request = GetRestRequet( + XApiAccountEndpoint.UpdateApplication, + @params: new Dictionary { + { XParam.XId.GetStringValue (), id.ToString() } + } + ); request.AddJsonBody(item); // @@ -181,7 +190,7 @@ namespace xIdentityService.Providers // var request = GetRestRequet( XApiAccountEndpoint.GetApplication, - @params: new Dictionary { + @params: new Dictionary { { XParam.XId.GetStringValue (), id.ToString() } } ); @@ -227,7 +236,7 @@ namespace xIdentityService.Providers // // Attach XQuery to Request ... - request = request.AttachXQuery (query); + request = request.AttachXQuery(query); // var response = await RunRestRequest>( @@ -307,7 +316,7 @@ namespace xIdentityService.Providers // var request = GetRestRequet( XApiAccountEndpoint.GetApiKey, - @params: new Dictionary { + @params: new Dictionary { { XParam.XId.GetStringValue (), id.ToString() } } ); @@ -351,7 +360,7 @@ namespace xIdentityService.Providers // var request = GetRestRequet( XApiAccountEndpoint.RemoveApiKey, - @params: new Dictionary { + @params: new Dictionary { { XParam.XId.GetStringValue (), id.ToString() } } ); @@ -369,11 +378,13 @@ namespace xIdentityService.Providers /// Update Specified ApiKey ... /// /// + /// /// /// /// public async Task UpdateApiKey( XTokenResponse tokens, + Guid id, XApiKeyDto item, CancellationToken cancellationToken = default ) @@ -382,12 +393,17 @@ namespace xIdentityService.Providers // Validate Args ... await validationProvider .GroupValidationBuilder() + .AddIsGuid(id) .AddNotNull(item) .AddNotNull(tokens) .AddNotEmpty( tokens.AccessToken ) .ValidateGroupAsync(); + if (id != item.Id) + { + XException.InvalidArgs.Throw(); + } // var client = GetRestClient(tokens); @@ -395,8 +411,8 @@ namespace xIdentityService.Providers // var request = GetRestRequet( XApiAccountEndpoint.UpdateApiKey, - @params: new Dictionary { - { XParam.XId.GetStringValue (), item.Id.ToString() } + @params: new Dictionary { + { XParam.XId.GetStringValue (), id.ToString() } } ); request.AddJsonBody(item); @@ -442,7 +458,7 @@ namespace xIdentityService.Providers // // Attach XQuery to Request ... - request = request.AttachXQuery (query); + request = request.AttachXQuery(query); // var response = await RunRestRequest>( @@ -565,7 +581,7 @@ namespace xIdentityService.Providers // var request = GetRestRequet( XApiAccountEndpoint.GetApiKeyUsage, - @params: new Dictionary { + @params: new Dictionary { { XParam.XId.GetStringValue (), id.ToString() } } ); @@ -612,7 +628,7 @@ namespace xIdentityService.Providers // var request = GetRestRequet( XApiAccountEndpoint.RemoveApiKeyUsage, - @params: new Dictionary { + @params: new Dictionary { { XParam.XId.GetStringValue (), id.ToString() } } ); @@ -630,11 +646,13 @@ namespace xIdentityService.Providers /// Update Specified Api Key Usage ... /// /// + /// /// /// /// public async Task UpdateApiKeyUsage( XTokenResponse tokens, + long id, XApiKeyUsageDto item, CancellationToken cancellationToken = default ) @@ -649,6 +667,9 @@ namespace xIdentityService.Providers tokens.AccessToken ) .ValidateGroupAsync(); + if (id <= 0 || id != item.Id) { + XException.InvalidArgs.Throw(); + } // var client = GetRestClient(tokens); @@ -658,7 +679,7 @@ namespace xIdentityService.Providers XApiAccountEndpoint.UpdateApiKeyUsage, @params: new Dictionary { - { XParam.XId.GetStringValue (), item.Id.ToString() } + { XParam.XId.GetStringValue (), id.ToString() } } ); request.AddJsonBody(item); @@ -704,7 +725,7 @@ namespace xIdentityService.Providers // // Attach XQuery to Request ... - request = request.AttachXQuery (query); + request = request.AttachXQuery(query); // var response = await RunRestRequest>( @@ -790,7 +811,7 @@ namespace xIdentityService.Providers // var request = GetRestRequet( XApiAccountEndpoint.ShowApiKey, - @params: new Dictionary { + @params: new Dictionary { { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } } @@ -841,9 +862,9 @@ namespace xIdentityService.Providers // var request = GetRestRequet( XApiAccountEndpoint.CreateApiKey, - @params: new Dictionary { + @params: new Dictionary { { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } - } + } ); request.AddJsonBody(createRequest); @@ -891,8 +912,8 @@ namespace xIdentityService.Providers // var request = GetRestRequet( - XApiAccountEndpoint.RemoveApiKey, - @params: new Dictionary { + XApiAccountEndpoint.RemoveApiKeyCustom, + @params: new Dictionary { { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } } @@ -945,7 +966,7 @@ namespace xIdentityService.Providers // var request = GetRestRequet( XApiAccountEndpoint.RotateApiKey, - @params: new Dictionary { + @params: new Dictionary { { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } } @@ -997,7 +1018,7 @@ namespace xIdentityService.Providers // var request = GetRestRequet( XApiAccountEndpoint.RevokeApiKey, - @params: new Dictionary { + @params: new Dictionary { { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } } @@ -1045,7 +1066,7 @@ namespace xIdentityService.Providers // var request = GetRestRequet( XApiAccountEndpoint.GetApiKeys, - @params: new Dictionary { + @params: new Dictionary { { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } } ); @@ -1095,7 +1116,7 @@ namespace xIdentityService.Providers // var request = GetRestRequet( XApiAccountEndpoint.GetApiKeyUsages, - @params: new Dictionary { + @params: new Dictionary { { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } } @@ -1132,7 +1153,7 @@ namespace xIdentityService.Providers var client = GetRestClient(); // - var checksum = SecurityProvider.Encrypt(validationRequest.ToJson()).ToMd5String(); + var checksum = SecurityProvider.Encrypt(validationRequest.ToJSON()).ToMd5String(); // var request = GetRestRequet( @@ -1141,6 +1162,7 @@ namespace xIdentityService.Providers { XHeader.ChecksumDigest.GetStringValue(), checksum } } ); + request.AddJsonBody(validationRequest); // var response = await RunRestRequest(