last ...
This commit is contained in:
@@ -1,12 +1,11 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using xIds.Helpers;
|
||||
using IdentityModel;
|
||||
using xIds.Interfaces;
|
||||
using xIdentityHelper;
|
||||
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;
|
||||
@@ -14,7 +13,6 @@ using xIdentityService.Constants;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace xIds.Providers
|
||||
{
|
||||
@@ -23,27 +21,27 @@ namespace xIds.Providers
|
||||
AllowMultiple = false,
|
||||
Inherited = true
|
||||
)]
|
||||
public class XApiKeyAuthorizationFilter : AuthorizeAttribute, IAuthorizationFilter
|
||||
public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter
|
||||
{
|
||||
// /// <summary>
|
||||
// /// Optional required scope for this endpoint.
|
||||
// /// Example: [XApiKeyAuthorizationFilter(RequiredScope = "read")]
|
||||
// /// </summary>
|
||||
// public string RequiredScope { get; set; }
|
||||
/// <summary>
|
||||
/// Optional allowed scopes. If empty, no scope enforcement.
|
||||
/// </summary>
|
||||
public XApiKeyScope[] Scopes { get; set; }
|
||||
|
||||
// /// <summary>
|
||||
// /// If false, a missing header will only result in NoResult (anonymous)
|
||||
// /// instead of a 401. Default is true (must provide a key).
|
||||
// /// </summary>
|
||||
// public bool ApiKeyRequired { get; set; } = true;
|
||||
public XApiKeyAccessAttribute(
|
||||
XApiKeyScope[] scopes = null
|
||||
)
|
||||
{
|
||||
//
|
||||
if (!scopes.HasChild())
|
||||
{
|
||||
scopes = [XApiKeyScope.Manage];
|
||||
}
|
||||
|
||||
// /// <summary>
|
||||
// /// Optional allowed scopes. If empty, no scope enforcement.
|
||||
// /// </summary>
|
||||
// public string[] AllowedScopes { get; set; }
|
||||
//
|
||||
Scopes = scopes;
|
||||
}
|
||||
|
||||
public XApiKeyAuthorizationFilter() { }
|
||||
|
||||
/// <summary>
|
||||
/// Authorization Filtering ...
|
||||
/// </summary>
|
||||
@@ -63,6 +61,8 @@ namespace xIds.Providers
|
||||
//
|
||||
// Access HttpContext ...
|
||||
var http = context.HttpContext;
|
||||
var error = XException.NotAuthorized.ToXError();
|
||||
var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue();
|
||||
|
||||
//
|
||||
try
|
||||
@@ -71,32 +71,6 @@ namespace xIds.Providers
|
||||
// Obtain the endpoint currently being executed
|
||||
var endpoint = http.GetEndpoint();
|
||||
|
||||
//
|
||||
// Retrieve all AuthorizeAttribute metadata from the endpoint
|
||||
var hasApiKeyScheme = false;
|
||||
var apiKeyScopes = XApiKeyHelper.GetXApiKeyScopes();
|
||||
var apiKeyPolicies = XApiKeyHelper.GetXApiKeyPolicies();
|
||||
var authorizeAttributes = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>();
|
||||
if (
|
||||
apiKeyPolicies.HasChild() &&
|
||||
authorizeAttributes.HasChild()
|
||||
)
|
||||
{
|
||||
//
|
||||
// Retrieve a List of ApiKey Policies ...
|
||||
hasApiKeyScheme = authorizeAttributes.Any(attr =>
|
||||
apiKeyPolicies.Any(asc => asc.ToNormalString() == attr.Policy.ToNormalString())
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
// if there is not any Policies for ApiKey Authentication
|
||||
// or Authorization, pass no Result ...
|
||||
if (!hasApiKeyScheme)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Retrieve the application provider from DI ...
|
||||
var applicationProvider = http.RequestServices
|
||||
@@ -105,18 +79,19 @@ namespace xIds.Providers
|
||||
if (applicationProvider.IsNull())
|
||||
{
|
||||
//
|
||||
context.Result = new UnauthorizedObjectResult("Provider Service Not Registered ...");
|
||||
error.Message = "Api Key Service not Registered ...";
|
||||
context.Result = new UnauthorizedObjectResult(error.ToJSON());
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Checking Header ...
|
||||
var apiKeyHeader = XHeader.ApiKey.GetStringValue();
|
||||
var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue();
|
||||
if (!http.Request.Headers.ContainsKey(apiKeyHeader))
|
||||
{
|
||||
//
|
||||
context.Result = new UnauthorizedObjectResult("ApiKey not Exists ...");
|
||||
error.Message = "ApiKey not Exists ...";
|
||||
context.Result = new UnauthorizedObjectResult(error.ToJSON());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -126,7 +101,8 @@ namespace xIds.Providers
|
||||
if (apiKey.IsNullOrEmpty())
|
||||
{
|
||||
//
|
||||
context.Result = new UnauthorizedObjectResult("ApiKey not Provided ...");
|
||||
error.Message = "ApiKey not Provided ...";
|
||||
context.Result = new UnauthorizedObjectResult(error.ToJSON());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -145,7 +121,8 @@ namespace xIds.Providers
|
||||
{
|
||||
//
|
||||
var message = validationResult.Errors.ToListString('\n');
|
||||
context.Result = new UnauthorizedObjectResult(message);
|
||||
error.Message = message;
|
||||
context.Result = new UnauthorizedObjectResult(error.ToJSON());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -185,7 +162,9 @@ namespace xIds.Providers
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.Result = new UnauthorizedObjectResult("ApiKey authorization failed ...");
|
||||
//
|
||||
error.Message = "ApiKey authorization failed ...";
|
||||
context.Result = new UnauthorizedObjectResult(error.ToJSON());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
using System.Linq;
|
||||
using xIds.Helpers;
|
||||
using IdentityModel;
|
||||
using xIds.Interfaces;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Extensions;
|
||||
using System.Threading.Tasks;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using xIdentityService.Constants;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
|
||||
namespace xIds.Providers
|
||||
{
|
||||
/// <summary>
|
||||
/// an Authentication Handler for ApiKey's based App's ...
|
||||
/// </summary>
|
||||
public class XApiKeyAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||||
{
|
||||
private readonly IXApplicationProvider applicationProvider;
|
||||
|
||||
//
|
||||
public string HeaderName { get; } = XHeader.ApiKey.GetStringValue();
|
||||
public string AuthenticationScheme { get; } = XAuthenticationScheme.XApiKey.GetStringValue();
|
||||
|
||||
public XApiKeyAuthenticationHandler(
|
||||
UrlEncoder encoder,
|
||||
ISystemClock clock,
|
||||
ILoggerFactory logger,
|
||||
IXApplicationProvider applicationProvider,
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options
|
||||
) : base(options, logger, encoder, clock)
|
||||
{
|
||||
this.applicationProvider = applicationProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle Authentication ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
//
|
||||
// Obtain the endpoint currently being executed
|
||||
var endpoint = Context.GetEndpoint();
|
||||
|
||||
//
|
||||
// Retrieve all AuthorizeAttribute metadata from the endpoint
|
||||
var hasApiKeyScheme = false;
|
||||
var apiKeyScopes = XApiKeyHelper.GetXApiKeyScopes();
|
||||
var apiKeyPolicies = XApiKeyHelper.GetXApiKeyPolicies();
|
||||
var authorizeAttributes = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>();
|
||||
if (
|
||||
apiKeyPolicies.HasChild() &&
|
||||
authorizeAttributes.HasChild()
|
||||
)
|
||||
{
|
||||
//
|
||||
// Retrieve a List of ApiKey Policies ...
|
||||
hasApiKeyScheme = authorizeAttributes.Any(attr =>
|
||||
apiKeyPolicies.Any(asc => asc.ToNormalString() == attr.Policy.ToNormalString()) ||
|
||||
attr.AuthenticationSchemes.ToNormalString() == XAuthenticationScheme.XApiKey.GetStringValue().ToNormalString()
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
// if there is not any Policies for ApiKey Authentication
|
||||
// or Authorization, pass no Result ...
|
||||
if (!hasApiKeyScheme)
|
||||
{
|
||||
return AuthenticateResult.NoResult();
|
||||
}
|
||||
|
||||
//
|
||||
var apiKeyHeader = HeaderName;
|
||||
if (!Request.Headers.ContainsKey(apiKeyHeader))
|
||||
{
|
||||
return AuthenticateResult.Fail("ApiKey not Exists ...");
|
||||
}
|
||||
|
||||
//
|
||||
var apiKey = Request.Headers[apiKeyHeader].ToString();
|
||||
if (apiKey.IsNullOrEmpty())
|
||||
{
|
||||
return AuthenticateResult.Fail("ApiKey not Provided ...");
|
||||
}
|
||||
|
||||
// Extract Client IP ...
|
||||
var clientIP = 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');
|
||||
return AuthenticateResult.Fail(message);
|
||||
}
|
||||
|
||||
//
|
||||
// Creating Claims ...
|
||||
var claims = new List<Claim> {
|
||||
//
|
||||
// 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, "apikey"),
|
||||
};
|
||||
|
||||
//
|
||||
// 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, Scheme.Name);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, Scheme.Name);
|
||||
|
||||
//
|
||||
return AuthenticateResult.Success(ticket);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -429,10 +429,12 @@ namespace xIds.Providers
|
||||
|
||||
//
|
||||
// Here we Have to Parse Allowed Ips and Scopes ...
|
||||
var allowedIps = (keyModel.AllowedIPs ?? string.Empty)
|
||||
.ParseListString<string>();
|
||||
var allowedScopes = (keyModel.AllowedScopes ?? string.Empty)
|
||||
.FromJSON<IEnumerable<string>>();
|
||||
var allowedIps = keyModel.AllowedIPs.IsNullOrEmpty()
|
||||
? []
|
||||
: keyModel.AllowedIPs.ParseListString<string>();
|
||||
var allowedScopes = keyModel.AllowedScopes.IsNullOrEmpty()
|
||||
? []
|
||||
: keyModel.AllowedScopes.FromJSON<IEnumerable<string>>();
|
||||
result.Scopes = [.. allowedScopes];
|
||||
|
||||
//
|
||||
|
||||
Reference in New Issue
Block a user