using System; using IdentityModel; using xIds.Interfaces; using xCommons.Constants; using xCommons.Extensions; using xExceptions.Constants; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using xIdentityModels.Constants; using xIdentityService.Constants; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Authorization; namespace xIds.Providers { [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.Manage]; } // Scopes = scopes; } /// /// Authorization Filtering ... /// /// public void OnAuthorization(AuthorizationFilterContext context) { Task.FromResult(OnAuthorizationAsync(context)); } /// /// Handle Authorization Filtering Using Tasks ... /// /// /// private async Task OnAuthorizationAsync(AuthorizationFilterContext context) { // // Access HttpContext ... var http = context.HttpContext; var error = XException.NotAuthorized.ToXError(); var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue(); // try { // // Obtain the endpoint currently being executed var endpoint = http.GetEndpoint(); // // Retrieve the application provider from DI ... var applicationProvider = http.RequestServices .GetService(typeof(IXApplicationProvider)) as IXApplicationProvider; if (applicationProvider.IsNull()) { // error.Message = "Api Key Service not Registered ..."; context.Result = new UnauthorizedObjectResult(error.ToJSON()); return; } // // Checking Header ... var apiKeyHeader = XHeader.ApiKey.GetStringValue(); if (!http.Request.Headers.ContainsKey(apiKeyHeader)) { // error.Message = "ApiKey not Exists ..."; context.Result = new UnauthorizedObjectResult(error.ToJSON()); 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.ToJSON()); return; } // // Extract Client IP ... var clientIP = http.Request.HttpContext.Connection.RemoteIpAddress?.ToString(); // // Validating ApiKey ... var validationResult = await applicationProvider .ValidateApiKey( apiKey: apiKey, clientIP: clientIP ); if (validationResult.Errors.HasChild()) { // var message = validationResult.Errors.ToListString('\n'); error.Message = message; context.Result = new UnauthorizedObjectResult(error.ToJSON()); return; } // // Creating Claims ... var claims = new List { // // Owner Identifier of API Key ... new(ClaimTypes.Name, validationResult.OwnerId), new(JwtClaimTypes.Subject, validationResult.OwnerId), // // Application Id ... new(XCustomClaims.ApplicationId, validationResult.ApplicationId.ToString()), // // Authentication Type ... new(XCustomClaims.AuthType, apiKeyAuthentication), }; // // Add Scopes ... if (validationResult.Scopes != null) { // foreach (var scope in validationResult.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.ToJSON()); } } } }