Compare commits
11
Commits
f37ff01868
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7a00244df | ||
|
|
bdc8791822 | ||
|
|
4e114aa85a | ||
|
|
c2b2dd27c5 | ||
|
|
002882300d | ||
|
|
bc5efed076 | ||
|
|
c8669bf493 | ||
|
|
ad69ce5ebc | ||
|
|
19fece89bd | ||
|
|
cd9ee26c0f | ||
|
|
b6f20c9e79 |
@@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using xIdentityModels.Models;
|
||||
@@ -12,7 +11,6 @@ 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
|
||||
@@ -22,7 +20,7 @@ namespace xIdentityService.Attributes
|
||||
AllowMultiple = false,
|
||||
Inherited = true
|
||||
)]
|
||||
public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter
|
||||
public class XApiKeyAccessAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
|
||||
{
|
||||
/// <summary>
|
||||
/// Optional allowed scopes. If empty, no scope enforcement.
|
||||
@@ -41,51 +39,27 @@ namespace xIdentityService.Attributes
|
||||
|
||||
//
|
||||
Scopes = scopes;
|
||||
|
||||
//
|
||||
Policy = $"{XIdentityServiceConstants.PolicyCacheKeyPrefix}:{string.Join(";", Scopes)}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Authorization Filtering ...
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
public void OnAuthorization(AuthorizationFilterContext context)
|
||||
{
|
||||
Task.FromResult(OnAuthorizationAsync(context));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle Authorization Filtering Using Tasks ...
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
private async Task OnAuthorizationAsync(
|
||||
AuthorizationFilterContext context,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
|
||||
{
|
||||
//
|
||||
// Access HttpContext ...
|
||||
var http = context.HttpContext;
|
||||
var cancellationToken = http.RequestAborted;
|
||||
var error = XException.NotAuthorized.ToXError();
|
||||
var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue();
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Obtain the endpoint currently being executed
|
||||
var endpointFeature = http.Features.Get<IEndpointFeature>();
|
||||
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
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace xIdentityService.Authorization
|
||||
{
|
||||
public class XApiKeyRoleRequirement : IAuthorizationRequirement
|
||||
{
|
||||
public IReadOnlyCollection<string> Roles { get; }
|
||||
public XApiKeyRoleRequirement(IEnumerable<string> roles)
|
||||
{
|
||||
Roles = [.. roles ?? []];
|
||||
}
|
||||
}
|
||||
|
||||
public class XApiKeyRoleHandler : AuthorizationHandler<XApiKeyRoleRequirement>
|
||||
{
|
||||
protected override Task HandleRequirementAsync(
|
||||
AuthorizationHandlerContext context,
|
||||
XApiKeyRoleRequirement requirement
|
||||
)
|
||||
{
|
||||
//
|
||||
if (!requirement.Roles.Any())
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
//
|
||||
if (requirement.Roles.Any(context.User.IsInRole))
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
|
||||
//
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using IdentityModel;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace xIdentityService.Authorization
|
||||
{
|
||||
public class XApiKeyScopeRequirement : IAuthorizationRequirement
|
||||
{
|
||||
public IReadOnlyCollection<string> Scopes { get; }
|
||||
|
||||
public XApiKeyScopeRequirement(IEnumerable<string> scopes)
|
||||
{
|
||||
Scopes = [.. scopes ?? []];
|
||||
}
|
||||
}
|
||||
|
||||
public class XApiKeyScopeHandler : AuthorizationHandler<XApiKeyScopeRequirement>
|
||||
{
|
||||
protected override Task HandleRequirementAsync(
|
||||
AuthorizationHandlerContext context,
|
||||
XApiKeyScopeRequirement requirement
|
||||
)
|
||||
{
|
||||
//
|
||||
if (!requirement.Scopes.Any())
|
||||
{
|
||||
//
|
||||
context.Succeed(requirement);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
//
|
||||
var userScopes = new HashSet<string>(
|
||||
context.User
|
||||
.FindAll(JwtClaimTypes.Scope)
|
||||
.SelectMany(c => c.Value.Split([' '], StringSplitOptions.RemoveEmptyEntries)),
|
||||
StringComparer.OrdinalIgnoreCase
|
||||
);
|
||||
|
||||
//
|
||||
if (requirement.Scopes.All(s => userScopes.Contains(s)))
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
|
||||
//
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace xIdentityService.Constants
|
||||
{
|
||||
public struct XIdentityServiceConstants
|
||||
{
|
||||
public const string PolicyCacheKeyPrefix = "XAuth:Cache";
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using xCommons.Authorization;
|
||||
using xHttpService.Interfaces;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using xIdentityService.Security;
|
||||
using xIdentityService.Constants;
|
||||
@@ -12,7 +14,6 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using IdentityModel.AspNetCore.OAuth2Introspection;
|
||||
using xHttpService.Interfaces;
|
||||
|
||||
namespace xIdentityService.DI
|
||||
{
|
||||
@@ -124,6 +125,22 @@ namespace xIdentityService.DI
|
||||
source.AddSingleton<IXPolicyHandler, XPolicyHandler>();
|
||||
}
|
||||
|
||||
public static void AddXRoleHierarchyResolver(
|
||||
this IServiceCollection source
|
||||
)
|
||||
{
|
||||
//
|
||||
// Check Provider ...
|
||||
var providerService = source.GetRegisteredService<IXRoleProvider>();
|
||||
if (providerService.IsNull())
|
||||
{
|
||||
XException.InvalidConfiguration.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
source.AddScoped<IXRoleHierarchyResolver, XRoleHierarchyResolver>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use Authentication
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
using xIdentityService.Models;
|
||||
using xIdentityService.Interfaces;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace xIdentityService.Extensions
|
||||
{
|
||||
public static class XAuthorizationExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Add Authorization Cache ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
public static void AddXAuthorizationCache(
|
||||
this IServiceCollection source
|
||||
)
|
||||
{
|
||||
source.AddSingleton<IXAuthorizationCache, XAuthorizationCache>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,24 @@
|
||||
using System.Linq;
|
||||
using xModels.Dtos;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Dtos;
|
||||
using xIdentityService.Models;
|
||||
using xIdentityModels.Models;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using xCommons.Authorization;
|
||||
using IdentityModel;
|
||||
using xCommons.Constants;
|
||||
|
||||
namespace xIdentityService.Extensions
|
||||
{
|
||||
public static class XModelExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts OpenActionUserInfoDto to XPersonDto ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static XPersonDto ToXPersonDto(this XOpenActionUserInfoDto source)
|
||||
{
|
||||
//
|
||||
@@ -20,5 +34,260 @@ namespace xIdentityService.Extensions
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check an Authorization which Can Applyed or not ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static bool HasRequirements(
|
||||
this XEffectiveAuthorizationDto source
|
||||
)
|
||||
{
|
||||
//
|
||||
var result =
|
||||
!source.IsNullOrDefault() &&
|
||||
!source.PolicyName.IsNullOrEmpty() &&
|
||||
source.RequireEnabledUser ||
|
||||
source.RequireAuthenticatedUser ||
|
||||
source.EffectiveRoles.HasChild() ||
|
||||
source.EffectiveScopes.HasChild() ||
|
||||
source.EffectiveClaims.HasChild();
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract Effective Authorization ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="effectiveRoles"></param>
|
||||
/// <returns></returns>
|
||||
public static XEffectiveAuthorizationDto ToEffectiveAuthorization(
|
||||
this XPolicyDefinition source,
|
||||
IEnumerable<string> effectiveRoles
|
||||
)
|
||||
{
|
||||
//
|
||||
XEffectiveAuthorizationDto result = null;
|
||||
if (source.IsNull() ||
|
||||
source.Name.IsNullOrEmpty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
result = new XEffectiveAuthorizationDto
|
||||
{
|
||||
//
|
||||
PolicyName = source.Name,
|
||||
EffectiveRoles = [.. effectiveRoles],
|
||||
RequireEnabledUser = source.RequireEnabledUser,
|
||||
RequireAuthenticatedUser = source.RequireAuthenticatedUser,
|
||||
EffectiveScopes = source.RequiredScopes
|
||||
.ParseListString<string>()?
|
||||
.ToHashSet() ?? [],
|
||||
EffectiveClaims = source.RequiredClaims.ToRequiredClaims()
|
||||
};
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract Effective Authorization ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="effectiveRoles"></param>
|
||||
/// <returns></returns>
|
||||
public static XEffectiveAuthorizationDto ToEffectiveAuthorization(
|
||||
this XPolicyDefinitionDto source,
|
||||
IEnumerable<string> effectiveRoles
|
||||
)
|
||||
{
|
||||
//
|
||||
XEffectiveAuthorizationDto result = null;
|
||||
if (source.IsNull() ||
|
||||
source.Name.IsNullOrEmpty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
var scopes = source.RequiredScopes.ParseListString<string>();
|
||||
result = new XEffectiveAuthorizationDto
|
||||
{
|
||||
PolicyName = source.Name,
|
||||
EffectiveScopes = scopes.HasChild()
|
||||
? [.. scopes]
|
||||
: [],
|
||||
EffectiveRoles = effectiveRoles.HasChild()
|
||||
? [.. effectiveRoles]
|
||||
: [],
|
||||
RequireEnabledUser = source.RequireEnabledUser,
|
||||
EffectiveClaims = source.RequiredClaims.ToRequiredClaims(),
|
||||
RequireAuthenticatedUser = source.RequireAuthenticatedUser
|
||||
};
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Merge to Effective Authorization Samples ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="other"></param>
|
||||
/// <returns></returns>
|
||||
public static XEffectiveAuthorizationDto MergeWith(
|
||||
this XEffectiveAuthorizationDto source,
|
||||
XEffectiveAuthorizationDto other
|
||||
)
|
||||
{
|
||||
//
|
||||
if (source.IsNull()) return other;
|
||||
if (other.IsNull()) return source;
|
||||
|
||||
//
|
||||
// Roles
|
||||
var mergedRoles = new HashSet<string>(source.EffectiveRoles);
|
||||
mergedRoles.UnionWith(other.EffectiveRoles);
|
||||
|
||||
//
|
||||
// Scopes
|
||||
var mergedScopes = new HashSet<string>(source.EffectiveScopes);
|
||||
mergedScopes.UnionWith(other.EffectiveScopes);
|
||||
|
||||
//
|
||||
// Claims
|
||||
var mergedClaims = new List<XRequiredClaimDto>(source.EffectiveClaims);
|
||||
mergedClaims.AddRange(other.EffectiveClaims);
|
||||
|
||||
//
|
||||
var result = new XEffectiveAuthorizationDto
|
||||
{
|
||||
//
|
||||
EffectiveRoles = mergedRoles,
|
||||
EffectiveScopes = mergedScopes,
|
||||
EffectiveClaims = mergedClaims,
|
||||
PolicyName = source.PolicyName ?? other.PolicyName,
|
||||
RequireEnabledUser =
|
||||
source.RequireEnabledUser || other.RequireEnabledUser,
|
||||
RequireAuthenticatedUser =
|
||||
source.RequireAuthenticatedUser || other.RequireAuthenticatedUser,
|
||||
};
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Make Authorization Policy Based on Dynamically loaded Descriptions ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static AuthorizationPolicy ToAuthorizationPolicy(
|
||||
this XEffectiveAuthorizationDto source
|
||||
)
|
||||
{
|
||||
//
|
||||
AuthorizationPolicy result = null;
|
||||
if (source.IsNull() ||
|
||||
source.PolicyName.IsNullOrEmpty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
var builder = new AuthorizationPolicyBuilder();
|
||||
|
||||
//
|
||||
// Check and Handle Authenticated User ...
|
||||
if (source.RequireAuthenticatedUser)
|
||||
{
|
||||
builder.RequireAuthenticatedUser();
|
||||
}
|
||||
|
||||
//
|
||||
// Check and Apply Effective Roles ...
|
||||
if (source.EffectiveRoles.HasChild())
|
||||
{
|
||||
//
|
||||
builder
|
||||
.AddRequirements(new RequiredRolesRequirement([.. source.EffectiveRoles]));
|
||||
}
|
||||
|
||||
//
|
||||
// Check and Apply Effective Scopes ...
|
||||
if (source.EffectiveScopes.HasChild())
|
||||
{
|
||||
//
|
||||
builder.RequireClaim(
|
||||
JwtClaimTypes.Scope,
|
||||
[.. source.EffectiveScopes]);
|
||||
}
|
||||
|
||||
//
|
||||
// Check and Apply Effective Claims ...
|
||||
foreach (var claim in source.EffectiveClaims)
|
||||
{
|
||||
//
|
||||
// Validate Type ...
|
||||
if (claim.Type.IsNullOrEmpty())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
if (claim.Values.HasChild())
|
||||
{
|
||||
//
|
||||
builder
|
||||
.RequireClaim(
|
||||
claim.Type,
|
||||
[.. claim.Values]);
|
||||
}
|
||||
else
|
||||
{
|
||||
builder.RequireClaim(claim.Type);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Check, Apply and Handle
|
||||
// IsBanned and IsEnabled Claims ...
|
||||
if (source.RequireEnabledUser &&
|
||||
source.RequireAuthenticatedUser)
|
||||
{
|
||||
//
|
||||
builder.RequireClaim(
|
||||
XCustomClaims.IsBanned,
|
||||
false.ToString(),
|
||||
false.ToString()
|
||||
.ToNormalString());
|
||||
|
||||
//
|
||||
builder.RequireClaim(
|
||||
XCustomClaims.IsEnabled,
|
||||
true.ToString(),
|
||||
true.ToString()
|
||||
.ToNormalString());
|
||||
}
|
||||
|
||||
//
|
||||
// Last Validation ...
|
||||
if (!builder.Requirements.HasChild())
|
||||
{
|
||||
builder.RequireAuthenticatedUser();
|
||||
}
|
||||
|
||||
//
|
||||
// Build and Create Result ...
|
||||
result = builder.Build();
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using IdentityModel;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Dtos;
|
||||
using xIdentityModels.Models;
|
||||
using xCommons.Authorization;
|
||||
using xIdentityService.Models;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
@@ -12,73 +13,41 @@ namespace xIdentityService.Extensions
|
||||
{
|
||||
public static class XPolicyDefinitionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Split Comma Separated Values (same style as XTag.References) ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
// public static List<string> ToCsvList(this string source)
|
||||
// {
|
||||
// //
|
||||
// if (source.IsNullOrEmpty())
|
||||
// {
|
||||
// return [];
|
||||
// }
|
||||
|
||||
// //
|
||||
// return source
|
||||
// .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
|
||||
// .Select(s => s.Trim())
|
||||
// .Where(s => !s.IsNullOrEmpty())
|
||||
// .Distinct()
|
||||
// .ToList();
|
||||
// }
|
||||
|
||||
/// <summary>
|
||||
/// Join Values as Comma Separated String ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
// public static string ToCsv(this IEnumerable<string> source)
|
||||
// {
|
||||
// //
|
||||
// if (!source.HasChild())
|
||||
// {
|
||||
// return null;
|
||||
// }
|
||||
|
||||
// //
|
||||
// return string.Join(",", source
|
||||
// .Where(s => !s.IsNullOrEmpty())
|
||||
// .Select(s => s.Trim())
|
||||
// .Distinct());
|
||||
// }
|
||||
|
||||
/// <summary>
|
||||
/// Deserialize Json Array of Required Claims ...
|
||||
/// </summary>
|
||||
/// <param name="json"></param>
|
||||
/// <returns></returns>
|
||||
// public static List<XRequiredClaimDto> ToRequiredClaims(this string json)
|
||||
// {
|
||||
// }
|
||||
public static List<XRequiredClaimDto> ToRequiredClaims(this string json)
|
||||
{
|
||||
//
|
||||
var result = new List<XRequiredClaimDto>();
|
||||
|
||||
/// <summary>
|
||||
/// Serialize Required Claims to Json ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
// public static string ToRequiredClaimsJson(this IEnumerable<XRequiredClaimDto> source)
|
||||
// {
|
||||
// //
|
||||
// if (!source.HasChild())
|
||||
// {
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// Validate ...
|
||||
if (json.IsNullOrEmpty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
// //
|
||||
// return JsonConvert.SerializeObject(source);
|
||||
// }
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
result = json.FromJSON<List<XRequiredClaimDto>>();
|
||||
}
|
||||
catch
|
||||
{ }
|
||||
|
||||
//
|
||||
if (result.IsNull())
|
||||
{
|
||||
result = [];
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Build AuthorizationPolicy exactly like XAuthorizationHelper does ...
|
||||
@@ -86,91 +55,184 @@ namespace xIdentityService.Extensions
|
||||
/// <param name="source"></param>
|
||||
/// <param name="effectiveRoles">already resolved by IXRoleHierarchyResolver</param>
|
||||
/// <returns></returns>
|
||||
// public static AuthorizationPolicy ToAuthorizationPolicy(
|
||||
// this XPolicyDefinition source,
|
||||
// IEnumerable<string> effectiveRoles
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// if (source.IsNull() || source.Name.IsNullOrEmpty())
|
||||
// {
|
||||
// return null;
|
||||
// }
|
||||
public static AuthorizationPolicy ToAuthorizationPolicy(
|
||||
this XPolicyDefinition source,
|
||||
IEnumerable<string> effectiveRoles
|
||||
)
|
||||
{
|
||||
//
|
||||
if (source.IsNull() || source.Name.IsNullOrEmpty())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// //
|
||||
// var builder = new AuthorizationPolicyBuilder();
|
||||
//
|
||||
var builder = new AuthorizationPolicyBuilder();
|
||||
|
||||
// //
|
||||
// // Authenticated User ...
|
||||
// if (source.RequireAuthenticatedUser)
|
||||
// {
|
||||
// builder.RequireAuthenticatedUser();
|
||||
// }
|
||||
//
|
||||
// Authenticated User ...
|
||||
if (source.RequireAuthenticatedUser)
|
||||
{
|
||||
builder.RequireAuthenticatedUser();
|
||||
}
|
||||
|
||||
// //
|
||||
// // Roles (RequiredRolesRequirement, handled by RequiredRolesHandler) ...
|
||||
// if (effectiveRoles.HasChild())
|
||||
// {
|
||||
// builder.AddRequirements(new RequiredRolesRequirement(effectiveRoles.ToArray()));
|
||||
// }
|
||||
//
|
||||
// Roles (RequiredRolesRequirement, handled by RequiredRolesHandler) ...
|
||||
if (effectiveRoles.HasChild())
|
||||
{
|
||||
builder.AddRequirements(new RequiredRolesRequirement(effectiveRoles.ToArray()));
|
||||
}
|
||||
|
||||
// //
|
||||
// // Scopes ...
|
||||
// var scopes = source.RequiredScopes.ToCsvList();
|
||||
// if (scopes.HasChild())
|
||||
// {
|
||||
// builder.RequireClaim(JwtClaimTypes.Scope, scopes.ToArray());
|
||||
// }
|
||||
//
|
||||
// Scopes ...
|
||||
var scopes = source.RequiredScopes.ParseListString<string>();
|
||||
if (scopes.HasChild())
|
||||
{
|
||||
builder.RequireClaim(JwtClaimTypes.Scope, [.. scopes]);
|
||||
}
|
||||
|
||||
// //
|
||||
// // Custom Claims ...
|
||||
// foreach (var claim in source.RequiredClaims.ToRequiredClaims())
|
||||
// {
|
||||
// //
|
||||
// if (claim.Type.IsNullOrEmpty())
|
||||
// {
|
||||
// continue;
|
||||
// }
|
||||
//
|
||||
// Custom Claims ...
|
||||
foreach (var claim in source.RequiredClaims.ToRequiredClaims())
|
||||
{
|
||||
//
|
||||
if (claim.Type.IsNullOrEmpty())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// //
|
||||
// if (claim.Values.HasChild())
|
||||
// {
|
||||
// builder.RequireClaim(claim.Type, claim.Values.ToArray());
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// builder.RequireClaim(claim.Type);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
if (claim.Values.HasChild())
|
||||
{
|
||||
builder.RequireClaim(claim.Type, claim.Values.ToArray());
|
||||
}
|
||||
else
|
||||
{
|
||||
builder.RequireClaim(claim.Type);
|
||||
}
|
||||
}
|
||||
|
||||
// //
|
||||
// // Enabled User (IsBanned=false & IsEnabled=true) ...
|
||||
// if (source.RequireEnabledUser)
|
||||
// {
|
||||
// //
|
||||
// builder.RequireClaim(
|
||||
// XCustomClaims.IsBanned,
|
||||
// false.ToString(),
|
||||
// false.ToString().ToNormalString()
|
||||
// );
|
||||
//
|
||||
// Enabled User (IsBanned=false & IsEnabled=true) ...
|
||||
if (source.RequireEnabledUser)
|
||||
{
|
||||
//
|
||||
builder.RequireClaim(
|
||||
XCustomClaims.IsBanned,
|
||||
false.ToString(),
|
||||
false.ToString().ToNormalString()
|
||||
);
|
||||
|
||||
// //
|
||||
// builder.RequireClaim(
|
||||
// XCustomClaims.IsEnabled,
|
||||
// true.ToString(),
|
||||
// true.ToString().ToNormalString()
|
||||
// );
|
||||
// }
|
||||
//
|
||||
builder.RequireClaim(
|
||||
XCustomClaims.IsEnabled,
|
||||
true.ToString(),
|
||||
true.ToString().ToNormalString()
|
||||
);
|
||||
}
|
||||
|
||||
// //
|
||||
// // Nothing Required => at least Deny Anonymous to avoid an Empty Policy ...
|
||||
// if (!builder.Requirements.HasChild())
|
||||
// {
|
||||
// builder.RequireAuthenticatedUser();
|
||||
// }
|
||||
//
|
||||
// Nothing Required => at least Deny Anonymous to avoid an Empty Policy ...
|
||||
if (!builder.Requirements.HasChild())
|
||||
{
|
||||
builder.RequireAuthenticatedUser();
|
||||
}
|
||||
|
||||
// //
|
||||
// return builder.Build();
|
||||
// }
|
||||
//
|
||||
return builder.Build();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Build AuthorizationPolicy exactly like XAuthorizationHelper does ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="effectiveRoles">already resolved by IXRoleHierarchyResolver</param>
|
||||
/// <returns></returns>
|
||||
public static AuthorizationPolicy ToAuthorizationPolicy(
|
||||
this XPolicyDefinitionDto source,
|
||||
IEnumerable<string> effectiveRoles
|
||||
)
|
||||
{
|
||||
//
|
||||
if (source.IsNull() || source.Name.IsNullOrEmpty())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
var builder = new AuthorizationPolicyBuilder();
|
||||
|
||||
//
|
||||
// Authenticated User ...
|
||||
if (source.RequireAuthenticatedUser)
|
||||
{
|
||||
builder.RequireAuthenticatedUser();
|
||||
}
|
||||
|
||||
//
|
||||
// Roles (RequiredRolesRequirement, handled by RequiredRolesHandler) ...
|
||||
if (effectiveRoles.HasChild())
|
||||
{
|
||||
builder.AddRequirements(new RequiredRolesRequirement(effectiveRoles.ToArray()));
|
||||
}
|
||||
|
||||
//
|
||||
// Scopes ...
|
||||
var scopes = source.RequiredScopes.ParseListString<string>();
|
||||
if (scopes.HasChild())
|
||||
{
|
||||
builder.RequireClaim(JwtClaimTypes.Scope, [.. scopes]);
|
||||
}
|
||||
|
||||
//
|
||||
// Custom Claims ...
|
||||
foreach (var claim in source.RequiredClaims.ToRequiredClaims())
|
||||
{
|
||||
//
|
||||
if (claim.Type.IsNullOrEmpty())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
if (claim.Values.HasChild())
|
||||
{
|
||||
builder.RequireClaim(claim.Type, claim.Values.ToArray());
|
||||
}
|
||||
else
|
||||
{
|
||||
builder.RequireClaim(claim.Type);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Enabled User (IsBanned=false & IsEnabled=true) ...
|
||||
if (source.RequireEnabledUser)
|
||||
{
|
||||
//
|
||||
builder.RequireClaim(
|
||||
XCustomClaims.IsBanned,
|
||||
false.ToString(),
|
||||
false.ToString().ToNormalString()
|
||||
);
|
||||
|
||||
//
|
||||
builder.RequireClaim(
|
||||
XCustomClaims.IsEnabled,
|
||||
true.ToString(),
|
||||
true.ToString().ToNormalString()
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
// Nothing Required => at least Deny Anonymous to avoid an Empty Policy ...
|
||||
if (!builder.Requirements.HasChild())
|
||||
{
|
||||
builder.RequireAuthenticatedUser();
|
||||
}
|
||||
|
||||
//
|
||||
return builder.Build();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using System.Linq;
|
||||
using xCommons.Extensions;
|
||||
using System.Security.Claims;
|
||||
using xIdentityModels.Models;
|
||||
using System.Threading.Tasks;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityService.Constants;
|
||||
using xIdentityModels.Extensions;
|
||||
using xIdentityService.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
|
||||
namespace xIdentityService.Handlers
|
||||
{
|
||||
public class XApiKeyAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||||
{
|
||||
private readonly IXIdentityProvider identityProvider;
|
||||
|
||||
public XApiKeyAuthenticationHandler(
|
||||
UrlEncoder encoder,
|
||||
ILoggerFactory logger,
|
||||
ISystemClock systemClock,
|
||||
IXIdentityProvider identityProvider,
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options
|
||||
) : base(options, logger, encoder, systemClock)
|
||||
{
|
||||
this.identityProvider = identityProvider;
|
||||
}
|
||||
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
//
|
||||
var header = XHeader.ApiKey.GetStringValue();
|
||||
if (!Request.Headers.TryGetValue(header, out var raw) ||
|
||||
raw.ToString().IsNullOrEmpty())
|
||||
{
|
||||
return await Task.FromResult(AuthenticateResult.NoResult());
|
||||
}
|
||||
|
||||
//
|
||||
var response = await identityProvider.ValidateApiKey(new XApiKeyValidationRequest
|
||||
{
|
||||
ApiKey = raw.ToString(),
|
||||
ClientIP = Context.Connection.RemoteIpAddress?.ToString()
|
||||
}, Context.RequestAborted);
|
||||
|
||||
//
|
||||
if (response.Errors.HasChild())
|
||||
{
|
||||
//
|
||||
return await Task.FromResult(
|
||||
AuthenticateResult.Fail(string.Join(",", response.Errors)));
|
||||
}
|
||||
|
||||
//
|
||||
var identity = new ClaimsIdentity(response.ToXClaims(), Scheme.Name);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
|
||||
//
|
||||
return await Task.FromResult(AuthenticateResult.Success(
|
||||
new AuthenticationTicket(principal, Scheme.Name)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace xIdentityService.Interfaces
|
||||
{
|
||||
public interface IXAuthorizationCache
|
||||
{
|
||||
void Clear();
|
||||
void RemovePolicy(string name);
|
||||
void SetPolicy(string name, AuthorizationPolicy policy);
|
||||
bool TryGetPolicy(string name, out AuthorizationPolicy policy);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
using xModels.Dtos;
|
||||
using System.Threading;
|
||||
using xIdentityModels.Dtos;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityModels.Models;
|
||||
using xIdentityService.Models;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xIdentityService.Interfaces
|
||||
{
|
||||
public interface IXAuthorizationProvider
|
||||
{
|
||||
//
|
||||
#region Scope ...
|
||||
Task<XQueryResult<XScopeDefinitionDto>> QueryScopesAsync(
|
||||
XQuery query,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XScopeDefinitionDto> GetScopeAsync(
|
||||
string name,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XScopeDefinitionDto> AddScopeAsync(
|
||||
XScopeDefinitionDto item,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XScopeDefinitionDto> UpdateScopeAsync(
|
||||
string name,
|
||||
XScopeDefinitionDto item,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<bool> RemoveScopeAsync(
|
||||
string name,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Role ...
|
||||
Task<IEnumerable<XRoleDefinitionDto>> GetRolesAsync(
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XRoleDefinitionDto> GetRoleAsync(
|
||||
string name,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XRoleDefinitionDto> AddRoleAsync(
|
||||
XRoleDefinitionDto item,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XRoleDefinitionDto> UpdateRoleAsync(
|
||||
string name,
|
||||
XRoleDefinitionDto item,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<bool> RemoveRoleAsync(
|
||||
string name,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<int> CountUsersInRoleAsync(
|
||||
string name,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XQueryResult<XRoleDefinitionDto>> QueryRolesAsync(
|
||||
XQuery query,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Policy ...
|
||||
Task<XQueryResult<XPolicyDefinitionDto>> QueryPoliciesAsync(
|
||||
XQuery query,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XPolicyDefinitionDto> GetPolicyAsync(
|
||||
string name,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XPolicyDefinitionDto> AddPolicyAsync(
|
||||
XPolicyDefinitionDto item,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XPolicyDefinitionDto> UpdatePolicyAsync(
|
||||
string name,
|
||||
XPolicyDefinitionDto item,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<bool> RemovePolicyAsync(
|
||||
string name,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XPolicyEvaluationResultDto> EvaluatePolicyAsync(
|
||||
string name,
|
||||
XUserClaimsInfoDto target,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
Task<XEffectiveAuthorizationDto> GetEffectiveAuthorizationAsync(
|
||||
XUserClaimsInfoDto target,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Utilities ...
|
||||
Task InvalidateAsync(string policyName = null);
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using xModels.Dtos;
|
||||
using System.Threading;
|
||||
using xIdentityModels.Dtos;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityModels.Models;
|
||||
using System.Linq.Expressions;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xIdentityService.Interfaces
|
||||
{
|
||||
public interface IXPolicyProvider
|
||||
{
|
||||
//
|
||||
#region Readers ...
|
||||
/// <summary>
|
||||
/// retrieve whole items as queryable ...
|
||||
/// </summary>
|
||||
/// <param name="asNoTracking">a flag for Tracking behaviour</param>
|
||||
/// <param name="predicate">an Expression for Filter Items ...</param>
|
||||
/// <param name="orderBuilder">an Order Builder expression for Ordering Query ...</param>
|
||||
/// <returns></returns>
|
||||
IQueryable<XPolicyDefinition> AsQueryable(
|
||||
bool asNoTracking = true,
|
||||
Expression<Func<XPolicyDefinition, bool>> predicate = null,
|
||||
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// retrieve an Entity by it's Id ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XPolicyDefinitionDto> GetAsync(
|
||||
int id,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// retrieve all exists Entities ...
|
||||
/// </summary>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="orderBuilder"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<XPolicyDefinitionDto>> GetAllAsync(
|
||||
bool ignoreSoftDeleteds = true,
|
||||
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// find an Entity by providing a Conditional Expression ...
|
||||
/// </summary>
|
||||
/// <param name="predicate"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XPolicyDefinitionDto> FindOneAsync(
|
||||
Expression<Func<XPolicyDefinition, bool>> predicate,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// find a collection of Entities by proving a Conditional Expression ...
|
||||
/// </summary>
|
||||
/// <param name="predicate"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="orderBuilder"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<XPolicyDefinitionDto>> FindManyAsync(
|
||||
Expression<Func<XPolicyDefinition, bool>> predicate,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// count all exists Entities ...
|
||||
/// </summary>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<int> CountAsync(
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// count all exists Entities Pages by providing page size ...
|
||||
/// </summary>
|
||||
/// <param name="pageSize"></param>
|
||||
/// <param name="totalItems"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<int> PagesCountAsync(
|
||||
int pageSize,
|
||||
int? totalItems = null,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Check an Entity exists or not ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<bool> IsExistsAsync(
|
||||
int id,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Query ...
|
||||
/// <summary>
|
||||
/// retrieve Entities based on XQuery Pagination structure ...
|
||||
/// </summary>
|
||||
/// <param name="query"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="predicate"></param>
|
||||
/// <param name="orderBuilder"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XQueryResult<XPolicyDefinitionDto>> QueryAsync(
|
||||
XQuery query,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
Expression<Func<XPolicyDefinition, bool>> predicate = null,
|
||||
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Add/Update/Remove ...
|
||||
/// <summary>
|
||||
/// add a new Entity ...
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
/// <param name="saveChanges"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XPolicyDefinitionDto> AddAsync(
|
||||
XPolicyDefinitionDto item,
|
||||
bool saveChanges = true,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Update an Entity values ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="item"></param>
|
||||
/// <param name="saveChanges"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XPolicyDefinitionDto> UpdateAsync(
|
||||
int id,
|
||||
XPolicyDefinitionDto item,
|
||||
bool saveChanges = true,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// remove an Entity by it's Id ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="softDelete"></param>
|
||||
/// <param name="saveChanges"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XPolicyDefinitionDto> RemoveAsync(
|
||||
int id,
|
||||
bool softDelete = true,
|
||||
bool saveChanges = true,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Custom ...
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Enrichers ...
|
||||
/// <summary>
|
||||
/// Enrich Item ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XPolicyDefinitionDto> EnrichAsync(
|
||||
XPolicyDefinition source,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Enrich Item ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XPolicyDefinitionDto> EnrichAsync(
|
||||
XPolicyDefinitionDto source,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Enrich a Collection of Items(s) ...
|
||||
/// </summary>
|
||||
/// <param name="sources"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<XPolicyDefinitionDto>> EnrichRangeAsync(
|
||||
IEnumerable<XPolicyDefinition> sources,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Enrich a Collection of Items(s) ...
|
||||
/// </summary>
|
||||
/// <param name="sources"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<XPolicyDefinitionDto>> EnrichRangeAsync(
|
||||
IEnumerable<XPolicyDefinitionDto> sources,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xIdentityService.Interfaces
|
||||
{
|
||||
public interface IXRoleHierarchyResolver
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieve All Enabled Role Names which Weight >= minWeight ...
|
||||
/// </summary>
|
||||
/// <param name="minWeight"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<string>> GetRolesByMinWeightAsync(
|
||||
int minWeight,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve Effective Roles for a Policy
|
||||
/// (explicit RequiredRoles ∪ roles by MinRoleWeight ∪ parents chain) ...
|
||||
/// </summary>
|
||||
/// <param name="explicitRoles"></param>
|
||||
/// <param name="minRoleWeight"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<string>> ResolveEffectiveRolesAsync(
|
||||
IEnumerable<string> explicitRoles,
|
||||
int? minRoleWeight,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using xModels.Dtos;
|
||||
using System.Threading;
|
||||
using xIdentityModels.Dtos;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityModels.Models;
|
||||
using System.Linq.Expressions;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xIdentityService.Interfaces
|
||||
{
|
||||
public interface IXRoleProvider
|
||||
{
|
||||
//
|
||||
#region Readers ...
|
||||
/// <summary>
|
||||
/// retrieve whole items as queryable ...
|
||||
/// </summary>
|
||||
/// <param name="asNoTracking">a flag for Tracking behaviour</param>
|
||||
/// <param name="predicate">an Expression for Filter Items ...</param>
|
||||
/// <param name="orderBuilder">an Order Builder expression for Ordering Query ...</param>
|
||||
/// <returns></returns>
|
||||
IQueryable<XRoleDefinition> AsQueryable(
|
||||
bool asNoTracking = true,
|
||||
Expression<Func<XRoleDefinition, bool>> predicate = null,
|
||||
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// retrieve an Entity by it's Id ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XRoleDefinitionDto> GetAsync(
|
||||
int id,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// retrieve all exists Entities ...
|
||||
/// </summary>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="orderBuilder"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<XRoleDefinitionDto>> GetAllAsync(
|
||||
bool ignoreSoftDeleteds = true,
|
||||
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// find an Entity by providing a Conditional Expression ...
|
||||
/// </summary>
|
||||
/// <param name="predicate"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XRoleDefinitionDto> FindOneAsync(
|
||||
Expression<Func<XRoleDefinition, bool>> predicate,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// find a collection of Entities by proving a Conditional Expression ...
|
||||
/// </summary>
|
||||
/// <param name="predicate"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="orderBuilder"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<XRoleDefinitionDto>> FindManyAsync(
|
||||
Expression<Func<XRoleDefinition, bool>> predicate,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// count all exists Entities ...
|
||||
/// </summary>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<int> CountAsync(
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// count all exists Entities Pages by providing page size ...
|
||||
/// </summary>
|
||||
/// <param name="pageSize"></param>
|
||||
/// <param name="totalItems"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<int> PagesCountAsync(
|
||||
int pageSize,
|
||||
int? totalItems = null,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Check an Entity exists or not ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<bool> IsExistsAsync(
|
||||
int id,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Query ...
|
||||
/// <summary>
|
||||
/// retrieve Entities based on XQuery Pagination structure ...
|
||||
/// </summary>
|
||||
/// <param name="query"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="predicate"></param>
|
||||
/// <param name="orderBuilder"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XQueryResult<XRoleDefinitionDto>> QueryAsync(
|
||||
XQuery query,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
Expression<Func<XRoleDefinition, bool>> predicate = null,
|
||||
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Add/Update/Remove ...
|
||||
/// <summary>
|
||||
/// add a new Entity ...
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
/// <param name="saveChanges"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XRoleDefinitionDto> AddAsync(
|
||||
XRoleDefinitionDto item,
|
||||
bool saveChanges = true,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Update an Entity values ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="item"></param>
|
||||
/// <param name="saveChanges"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XRoleDefinitionDto> UpdateAsync(
|
||||
int id,
|
||||
XRoleDefinitionDto item,
|
||||
bool saveChanges = true,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// remove an Entity by it's Id ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="softDelete"></param>
|
||||
/// <param name="saveChanges"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XRoleDefinitionDto> RemoveAsync(
|
||||
int id,
|
||||
bool softDelete = true,
|
||||
bool saveChanges = true,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Custom ...
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Enrichers ...
|
||||
/// <summary>
|
||||
/// Enrich Item ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XRoleDefinitionDto> EnrichAsync(
|
||||
XRoleDefinition source,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Enrich Item ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XRoleDefinitionDto> EnrichAsync(
|
||||
XRoleDefinitionDto source,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Enrich a Collection of Items(s) ...
|
||||
/// </summary>
|
||||
/// <param name="sources"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<XRoleDefinitionDto>> EnrichRangeAsync(
|
||||
IEnumerable<XRoleDefinition> sources,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Enrich a Collection of Items(s) ...
|
||||
/// </summary>
|
||||
/// <param name="sources"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<XRoleDefinitionDto>> EnrichRangeAsync(
|
||||
IEnumerable<XRoleDefinitionDto> sources,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
using System;
|
||||
using xModels.Dtos;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using xIdentityModels.Dtos;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityModels.Models;
|
||||
using System.Linq.Expressions;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xIdentityService.Interfaces
|
||||
{
|
||||
public interface IXScopeProvider
|
||||
{
|
||||
//
|
||||
#region Readers ...
|
||||
/// <summary>
|
||||
/// retrieve whole items as queryable ...
|
||||
/// </summary>
|
||||
/// <param name="asNoTracking">a flag for Tracking behaviour</param>
|
||||
/// <param name="predicate">an Expression for Filter Items ...</param>
|
||||
/// <param name="orderBuilder">an Order Builder expression for Ordering Query ...</param>
|
||||
/// <returns></returns>
|
||||
IQueryable<XScopeDefinition> AsQueryable(
|
||||
bool asNoTracking = true,
|
||||
Expression<Func<XScopeDefinition, bool>> predicate = null,
|
||||
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// retrieve an Entity by it's Id ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XScopeDefinitionDto> GetAsync(
|
||||
int id,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// retrieve all exists Entities ...
|
||||
/// </summary>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="orderBuilder"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<XScopeDefinitionDto>> GetAllAsync(
|
||||
bool ignoreSoftDeleteds = true,
|
||||
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// find an Entity by providing a Conditional Expression ...
|
||||
/// </summary>
|
||||
/// <param name="predicate"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XScopeDefinitionDto> FindOneAsync(
|
||||
Expression<Func<XScopeDefinition, bool>> predicate,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// find a collection of Entities by proving a Conditional Expression ...
|
||||
/// </summary>
|
||||
/// <param name="predicate"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="orderBuilder"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<XScopeDefinitionDto>> FindManyAsync(
|
||||
Expression<Func<XScopeDefinition, bool>> predicate,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// count all exists Entities ...
|
||||
/// </summary>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<int> CountAsync(
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// count all exists Entities Pages by providing page size ...
|
||||
/// </summary>
|
||||
/// <param name="pageSize"></param>
|
||||
/// <param name="totalItems"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<int> PagesCountAsync(
|
||||
int pageSize,
|
||||
int? totalItems = null,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Check an Entity exists or not ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<bool> IsExistsAsync(
|
||||
int id,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Query ...
|
||||
/// <summary>
|
||||
/// retrieve Entities based on XQuery Pagination structure ...
|
||||
/// </summary>
|
||||
/// <param name="query"></param>
|
||||
/// <param name="ignoreSoftDeleteds"></param>
|
||||
/// <param name="predicate"></param>
|
||||
/// <param name="orderBuilder"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XQueryResult<XScopeDefinitionDto>> QueryAsync(
|
||||
XQuery query,
|
||||
bool ignoreSoftDeleteds = true,
|
||||
Expression<Func<XScopeDefinition, bool>> predicate = null,
|
||||
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Add/Update/Remove ...
|
||||
/// <summary>
|
||||
/// add a new Entity ...
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
/// <param name="saveChanges"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XScopeDefinitionDto> AddAsync(
|
||||
XScopeDefinitionDto item,
|
||||
bool saveChanges = true,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Update an Entity values ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="item"></param>
|
||||
/// <param name="saveChanges"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XScopeDefinitionDto> UpdateAsync(
|
||||
int id,
|
||||
XScopeDefinitionDto item,
|
||||
bool saveChanges = true,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// remove an Entity by it's Id ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="softDelete"></param>
|
||||
/// <param name="saveChanges"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XScopeDefinitionDto> RemoveAsync(
|
||||
int id,
|
||||
bool softDelete = true,
|
||||
bool saveChanges = true,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Custom ...
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Enrichers ...
|
||||
/// <summary>
|
||||
/// Enrich Item ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XScopeDefinitionDto> EnrichAsync(
|
||||
XScopeDefinition source,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Enrich Item ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XScopeDefinitionDto> EnrichAsync(
|
||||
XScopeDefinitionDto source,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Enrich a Collection of Items(s) ...
|
||||
/// </summary>
|
||||
/// <param name="sources"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<XScopeDefinitionDto>> EnrichRangeAsync(
|
||||
IEnumerable<XScopeDefinition> sources,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Enrich a Collection of Items(s) ...
|
||||
/// </summary>
|
||||
/// <param name="sources"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<XScopeDefinitionDto>> EnrichRangeAsync(
|
||||
IEnumerable<XScopeDefinitionDto> sources,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using xIdentityService.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace xIdentityService.Models
|
||||
{
|
||||
public class XAuthorizationCache : IXAuthorizationCache
|
||||
{
|
||||
private readonly ILogger<XAuthorizationCache> logger;
|
||||
private readonly ConcurrentDictionary<string, AuthorizationPolicy> policies;
|
||||
|
||||
public XAuthorizationCache(
|
||||
ILogger<XAuthorizationCache> logger
|
||||
)
|
||||
{
|
||||
//
|
||||
this.logger = logger;
|
||||
policies = new ConcurrentDictionary<string, AuthorizationPolicy>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
policies.Clear();
|
||||
}
|
||||
|
||||
public void SetPolicy(
|
||||
string name,
|
||||
AuthorizationPolicy policy
|
||||
)
|
||||
{
|
||||
//
|
||||
if (name.IsNullOrEmpty() ||
|
||||
policy.IsNullOrDefault())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
policies.AddOrUpdate(name, policy, (_, __) => policy);
|
||||
}
|
||||
|
||||
public bool TryGetPolicy(
|
||||
string name,
|
||||
out AuthorizationPolicy policy
|
||||
)
|
||||
{
|
||||
//
|
||||
if (name.IsNullOrEmpty())
|
||||
{
|
||||
//
|
||||
policy = null!;
|
||||
return false;
|
||||
}
|
||||
|
||||
//
|
||||
var result = policies.TryGetValue(name, out policy!);
|
||||
return result;
|
||||
}
|
||||
|
||||
public void RemovePolicy(string name)
|
||||
{
|
||||
//
|
||||
if (name.IsNullOrEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
if (policies.TryRemove(name, out _)) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xIdentityService.Models
|
||||
{
|
||||
public class XEffectiveAuthorizationDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Policy Name ...
|
||||
/// </summary>
|
||||
public string PolicyName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Required Authenticated User ...
|
||||
/// </summary>
|
||||
public bool RequireAuthenticatedUser { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Check Policy has Enabled feature or not ...
|
||||
/// (IsEnabled/IsBanned) ...
|
||||
/// </summary>
|
||||
public bool RequireEnabledUser { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Effective Roles ...
|
||||
/// </summary>
|
||||
public HashSet<string> EffectiveRoles { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Effective Scopes ...
|
||||
/// </summary>
|
||||
public HashSet<string> EffectiveScopes { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Effective Claims ...
|
||||
/// </summary>
|
||||
public List<XRequiredClaimDto> EffectiveClaims { get; set; } = [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xIdentityService.Models
|
||||
{
|
||||
public class XPolicyEvaluationResultDto
|
||||
{
|
||||
public bool Passed { get; set; }
|
||||
public string Policy { get; set; }
|
||||
public List<string> FailedRequirements { get; set; } = [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xIdentityService.Models
|
||||
{
|
||||
public class XRequiredClaimDto
|
||||
{
|
||||
public string Type { get; set; }
|
||||
public List<string> Values { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using xModels.Dtos;
|
||||
using System.Threading;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Dtos;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityModels.Models;
|
||||
using xIdentityService.Models;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityService.Extensions;
|
||||
|
||||
namespace xIdentityService.Providers
|
||||
{
|
||||
public partial class XAuthorizationProvider
|
||||
{
|
||||
// //
|
||||
// #region Policy ...
|
||||
// public async Task<XPolicyDefinitionDto> AddPolicyAsync(
|
||||
// XPolicyDefinitionDto item,
|
||||
// XUserClaimsInfoDto userInfo,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Validate ...
|
||||
// if (item.IsNull() || item.Name.IsNullOrEmpty())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// var normalized = item.Name.ToNormalString();
|
||||
// var exists = await policies.FindOneAsync(
|
||||
// predicate: p => p.Name.ToLower() == normalized,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
// if (!exists.IsNull())
|
||||
// {
|
||||
// XException.Duplicate.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// await ValidateReferencesAsync(item, cancellationToken);
|
||||
|
||||
// //
|
||||
// item.IsSystem = false;
|
||||
|
||||
// //
|
||||
// var result = await policies.AddAsync(
|
||||
// item: item,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// await InvalidateAsync(result.Name);
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// public async Task<bool> RemovePolicyAsync(
|
||||
// string name,
|
||||
// XUserClaimsInfoDto userInfo,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// var entity = await FindPolicyOrThrowAsync(name, cancellationToken);
|
||||
// if (entity.IsSystem)
|
||||
// {
|
||||
// XException.NotAllowed.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// await policies.RemoveAsync(
|
||||
// id: entity.Id,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// await InvalidateAsync(entity.Name);
|
||||
// return true;
|
||||
// }
|
||||
|
||||
// public async Task<XQueryResult<XPolicyDefinitionDto>> QueryPoliciesAsync(
|
||||
// XQuery query,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Validate ...
|
||||
// if (query.IsNull())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// var result = await policies.QueryAsync(
|
||||
// query: query,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// public async Task<XPolicyDefinitionDto> GetPolicyAsync(
|
||||
// string name,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// var result = await FindPolicyOrThrowAsync(name, cancellationToken);
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// public async Task<XPolicyDefinitionDto> UpdatePolicyAsync(
|
||||
// string name,
|
||||
// XPolicyDefinitionDto item,
|
||||
// XUserClaimsInfoDto userInfo,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Validate ...
|
||||
// if (name.IsNullOrEmpty() || item.IsNull())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// var exists = await FindPolicyOrThrowAsync(name, cancellationToken);
|
||||
// if (exists.IsSystem)
|
||||
// {
|
||||
// XException.NotAllowed.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// // Referenced Roles & Scopes must exist ...
|
||||
// await ValidateReferencesAsync(item, cancellationToken);
|
||||
|
||||
// //
|
||||
// var result = await policies.UpdateAsync(
|
||||
// item: item,
|
||||
// id: exists.Id,
|
||||
// userInfo: userInfo,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// // Drop the cached policy so it rebuilds on next evaluation ...
|
||||
// await InvalidateAsync(result.Name);
|
||||
|
||||
// //
|
||||
// // Return the updated DTO as-is (EffectiveRoles is not a field on
|
||||
// // XPolicyDefinitionDto) ...
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// public async Task<XPolicyEvaluationResultDto> EvaluatePolicyAsync(
|
||||
// string name,
|
||||
// XUserClaimsInfoDto target,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Load the policy (throws NotFound when missing) ...
|
||||
// var dto = await FindPolicyOrThrowAsync(name, cancellationToken);
|
||||
|
||||
// //
|
||||
// var result = new XPolicyEvaluationResultDto
|
||||
// {
|
||||
// Passed = true,
|
||||
// Policy = dto.Name,
|
||||
// FailedRequirements = []
|
||||
// };
|
||||
|
||||
// //
|
||||
// // Build the policy's effective authorization via the shared helper
|
||||
// // (resolver + projection onto XEffectiveAuthorizationDto) ...
|
||||
// var auth = await ToDtoWithEffectiveRolesAsync(dto, cancellationToken);
|
||||
// if (auth.IsNull())
|
||||
// {
|
||||
// //
|
||||
// result.Passed = false;
|
||||
// result.FailedRequirements.Add("PolicyNotBuilt");
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// //
|
||||
// // Anonymous user fails any policy that requires authentication ...
|
||||
// if (target.IsNull())
|
||||
// {
|
||||
// //
|
||||
// if (auth.RequireAuthenticatedUser)
|
||||
// {
|
||||
// //
|
||||
// result.Passed = false;
|
||||
// result.FailedRequirements.Add("RequireAuthenticatedUser");
|
||||
// }
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// //
|
||||
// // Effective Roles: the user must hold at least one ...
|
||||
// if (auth.EffectiveRoles.HasChild())
|
||||
// {
|
||||
// //
|
||||
// // var userRoles = await roles.FindManyAsync(
|
||||
// // target.GetUserSelectByParam(),
|
||||
// // cancellationToken
|
||||
// // );
|
||||
|
||||
// //
|
||||
// var userSelectByParam = target.GetUserSelectByParam();
|
||||
|
||||
// //
|
||||
// var userRoles = await roles.FindManyAsync(
|
||||
// predicate: x => x.
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// var matched = auth.EffectiveRoles.Any(er =>
|
||||
// userRoles.Any(ur =>
|
||||
// string.Equals(ur, er, StringComparison.OrdinalIgnoreCase)
|
||||
// )
|
||||
// );
|
||||
|
||||
// //
|
||||
// if (!matched)
|
||||
// {
|
||||
// //
|
||||
// result.Passed = false;
|
||||
// result.FailedRequirements.Add("RequiredRoles");
|
||||
// }
|
||||
// }
|
||||
|
||||
// //
|
||||
// // NOTE: RequireEnabledUser (IsEnabled / !IsBanned), EffectiveScopes and
|
||||
// // EffectiveClaims checks are layered on here once the matching flags /
|
||||
// // collections on XUserClaimsInfoDto (xIdentityModels) are wired.
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// public async Task<XEffectiveAuthorizationDto> GetEffectiveAuthorizationAsync(
|
||||
// XUserClaimsInfoDto target,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// var result = new XEffectiveAuthorizationDto
|
||||
// {
|
||||
// RequireEnabledUser = !target.IsNull(),
|
||||
// RequireAuthenticatedUser = !target.IsNull(),
|
||||
// EffectiveClaims = new List<XRequiredClaimDto>(),
|
||||
// EffectiveRoles = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
|
||||
// EffectiveScopes = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
|
||||
// };
|
||||
|
||||
// //
|
||||
// if (target.IsNull())
|
||||
// {
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// //
|
||||
// // Effective roles = the user's actual roles (from RoleManager) ...
|
||||
// var userRoles = await roleSync.GetUserRolesAsync(
|
||||
// cancellationToken: cancellationToken,
|
||||
// userSelectByParam: target.GetUserSelectByParam()
|
||||
// );
|
||||
// foreach (var role in userRoles)
|
||||
// {
|
||||
// result.EffectiveRoles.Add(role);
|
||||
// }
|
||||
|
||||
// //
|
||||
// // NOTE: EffectiveScopes / EffectiveClaims aggregation is wired here from
|
||||
// // the user's scope / claim source on XUserClaimsInfoDto (xIdentityModels).
|
||||
// return result;
|
||||
// }
|
||||
// #endregion
|
||||
|
||||
// //
|
||||
// #region Private ...
|
||||
// #endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Dtos;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityModels.Models;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xIdentityService.Providers
|
||||
{
|
||||
public partial class XAuthorizationProvider
|
||||
{
|
||||
//
|
||||
// #region Role ...
|
||||
// public async Task<IEnumerable<XRoleDefinitionDto>> GetRolesAsync(
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// var result = await roles
|
||||
// .GetAllAsync(cancellationToken: cancellationToken);
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// public async Task<XRoleDefinitionDto> GetRoleAsync(
|
||||
// string name,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// var result = await FindRoleOrThrowAsync(name, cancellationToken);
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// public async Task<XRoleDefinitionDto> AddRoleAsync(
|
||||
// XRoleDefinitionDto item,
|
||||
// XUserClaimsInfoDto userInfo,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Validate ...
|
||||
// if (item.IsNull() || item.Name.IsNullOrEmpty())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// // Duplicate check ...
|
||||
// var normalized = item.Name.ToNormalString();
|
||||
// var exists = await roles.FindOneAsync(
|
||||
// predicate: r => r.Name.ToLower() == normalized,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
// if (!exists.IsNull())
|
||||
// {
|
||||
// XException.Duplicate.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// // Persist ...
|
||||
// item.IsSystem = false;
|
||||
// var result = await roles.AddAsync(
|
||||
// item: item,
|
||||
// userInfo: userInfo,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// // Sync to IdentityServer (RoleManager<IdentityRole>) ...
|
||||
// var entity = roles.AsQueryable()
|
||||
// .FirstOrDefault(r => r.Name.ToLower() == normalized);
|
||||
// if (!entity.IsNull())
|
||||
// {
|
||||
// await roleSync.UpsertAsync(entity, cancellationToken);
|
||||
// }
|
||||
|
||||
// //
|
||||
// await InvalidateAsync();
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// public async Task<XRoleDefinitionDto> UpdateRoleAsync(
|
||||
// string name,
|
||||
// XRoleDefinitionDto item,
|
||||
// XUserClaimsInfoDto userInfo,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Validate ...
|
||||
// if (name.IsNullOrEmpty() || item.IsNull())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// var existing = await FindRoleOrThrowAsync(name, cancellationToken);
|
||||
// if (existing.IsSystem)
|
||||
// {
|
||||
// XException.NotAllowed.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// var updated = await roles.UpdateAsync(
|
||||
// id: existing.Id,
|
||||
// item: item,
|
||||
// userInfo: userInfo,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// // Sync to IdentityServer ...
|
||||
// var entity = roles.AsQueryable()
|
||||
// .FirstOrDefault(r => r.Name.ToLower() == name.ToNormalString());
|
||||
// if (!entity.IsNull())
|
||||
// {
|
||||
// await roleSync.UpsertAsync(entity, cancellationToken);
|
||||
// }
|
||||
|
||||
// //
|
||||
// await InvalidateAsync();
|
||||
// return updated;
|
||||
// }
|
||||
|
||||
// public async Task<bool> RemoveRoleAsync(
|
||||
// string name,
|
||||
// XUserClaimsInfoDto userInfo,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// var exists = await FindRoleOrThrowAsync(name, cancellationToken);
|
||||
// if (exists.IsSystem)
|
||||
// {
|
||||
// XException.NotAllowed.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// await roles.RemoveAsync(
|
||||
// id: exists.Id,
|
||||
// userInfo: userInfo,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// // Remove from IdentityServer ...
|
||||
// await roleSync.RemoveAsync(name, cancellationToken);
|
||||
|
||||
// //
|
||||
// await InvalidateAsync();
|
||||
// return true;
|
||||
// }
|
||||
|
||||
// public async Task<int> CountUsersInRoleAsync(
|
||||
// string name,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Fail fast if the role itself does not exist ...
|
||||
// await FindRoleOrThrowAsync(name, cancellationToken);
|
||||
|
||||
// //
|
||||
// var result = await roleSync
|
||||
// .CountUsersInRoleAsync(
|
||||
// name,
|
||||
// cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
// #endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using xModels.Dtos;
|
||||
using System.Threading;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Dtos;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityModels.Models;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xIdentityService.Providers
|
||||
{
|
||||
public partial class XAuthorizationProvider
|
||||
{
|
||||
// //
|
||||
// #region Scope ...
|
||||
// public async Task<XQueryResult<XScopeDefinitionDto>> QueryScopesAsync(
|
||||
// XQuery query,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// if (query.IsNull())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// var result = await scopes.QueryAsync(
|
||||
// query: query,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// public async Task<XScopeDefinitionDto> GetScopeAsync(
|
||||
// string name,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// var result = await FindScopeOrThrowAsync(name, cancellationToken);
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// public async Task<XScopeDefinitionDto> AddScopeAsync(
|
||||
// XScopeDefinitionDto item,
|
||||
// XUserClaimsInfoDto userInfo,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Validate ...
|
||||
// if (item.IsNull() || item.Name.IsNullOrEmpty())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// // Duplicate check ...
|
||||
// var normalized = item.Name.ToNormalString();
|
||||
// var exists = await scopes.FindOneAsync(
|
||||
// cancellationToken: cancellationToken,
|
||||
// predicate: s => s.Name.ToLower() == normalized
|
||||
// );
|
||||
// if (!exists.IsNull())
|
||||
// {
|
||||
// XException.Duplicate.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// // Persist ...
|
||||
// item.IsSystem = false;
|
||||
// var result = await scopes.AddAsync(
|
||||
// item: item,
|
||||
// userInfo: userInfo,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// // Sync to IdentityServer (ConfigurationDbContext) ...
|
||||
// var entity = scopes.AsQueryable()
|
||||
// .FirstOrDefault(s => s.Name.ToLower() == normalized);
|
||||
// if (!entity.IsNull())
|
||||
// {
|
||||
// //
|
||||
// await scopeSync
|
||||
// .UpsertAsync(entity, cancellationToken);
|
||||
// }
|
||||
|
||||
// //
|
||||
// await InvalidateAsync();
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// public async Task<XScopeDefinitionDto> UpdateScopeAsync(
|
||||
// string name,
|
||||
// XScopeDefinitionDto item,
|
||||
// XUserClaimsInfoDto userInfo,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Validate ...
|
||||
// if (name.IsNullOrEmpty() || item.IsNull())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// var existing = await FindScopeOrThrowAsync(name, cancellationToken);
|
||||
// if (existing.IsSystem)
|
||||
// {
|
||||
// XException.NotAllowed.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// var updated = await scopes.UpdateAsync(
|
||||
// id: existing.Id,
|
||||
// item: item,
|
||||
// userInfo: userInfo,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// // Sync to IdentityServer ...
|
||||
// var entity = scopes.AsQueryable()
|
||||
// .FirstOrDefault(s => s.Name.ToLower() == name.ToNormalString());
|
||||
// if (!entity.IsNull())
|
||||
// {
|
||||
// await scopeSync.UpsertAsync(entity, cancellationToken);
|
||||
// }
|
||||
|
||||
// //
|
||||
// await InvalidateAsync();
|
||||
// return updated;
|
||||
// }
|
||||
|
||||
// public async Task<bool> RemoveScopeAsync(
|
||||
// string name,
|
||||
// XUserClaimsInfoDto userInfo,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// var entity = await FindScopeOrThrowAsync(name, cancellationToken);
|
||||
// if (entity.IsSystem)
|
||||
// {
|
||||
// XException.NotAllowed.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// await scopes.RemoveAsync(
|
||||
// id: entity.Id,
|
||||
// userInfo: userInfo,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// // Remove from IdentityServer ...
|
||||
// await scopeSync.RemoveAsync(name, cancellationToken);
|
||||
|
||||
// //
|
||||
// await InvalidateAsync();
|
||||
// return true;
|
||||
// }
|
||||
// #endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using System;
|
||||
using xCommons.Extensions;
|
||||
using xCommons.Configurations;
|
||||
using xIdentityService.Constants;
|
||||
using xIdentityService.Interfaces;
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
|
||||
namespace xIdentityService.Providers
|
||||
{
|
||||
/// <summary>
|
||||
/// Thread-safe local cache; IMemoryCache gives TTL,
|
||||
/// ConcurrentDictionary gives key tracking for Clear() ...
|
||||
/// </summary>
|
||||
public class XAuthorizationCache : IXAuthorizationCache
|
||||
{
|
||||
private readonly TimeSpan ttl;
|
||||
private readonly IMemoryCache cache;
|
||||
private readonly ConcurrentDictionary<string, byte> keys = new();
|
||||
private readonly XAppConfiguration appConfiguration;
|
||||
|
||||
public XAuthorizationCache(
|
||||
IMemoryCache cache,
|
||||
XAppConfiguration appConfiguration
|
||||
)
|
||||
{
|
||||
//
|
||||
this.cache = cache;
|
||||
this.appConfiguration = appConfiguration;
|
||||
ttl = TimeSpan.FromMinutes(appConfiguration.DefaultCacheTtlMinutes);
|
||||
}
|
||||
|
||||
public bool TryGetPolicy(
|
||||
string name,
|
||||
out AuthorizationPolicy policy
|
||||
)
|
||||
{
|
||||
//
|
||||
policy = null;
|
||||
|
||||
//
|
||||
var result =
|
||||
!name.IsNullOrEmpty() &&
|
||||
cache.TryGetValue(Key(name), out policy);
|
||||
return result;
|
||||
}
|
||||
|
||||
public void SetPolicy(
|
||||
string name,
|
||||
AuthorizationPolicy policy
|
||||
)
|
||||
{
|
||||
//
|
||||
if (name.IsNullOrEmpty() || policy.IsNull())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
cache.Set(Key(name), policy, ttl);
|
||||
keys[Key(name)] = 0;
|
||||
}
|
||||
|
||||
public void RemovePolicy(string name)
|
||||
{
|
||||
//
|
||||
if (name.IsNullOrEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
cache.Remove(Key(name));
|
||||
keys.TryRemove(Key(name), out _);
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
//
|
||||
foreach (var key in keys.Keys)
|
||||
{
|
||||
cache.Remove(key);
|
||||
}
|
||||
|
||||
//
|
||||
keys.Clear();
|
||||
}
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
private static string Key(string name) =>
|
||||
XIdentityServiceConstants.PolicyCacheKeyPrefix + name.ToNormalString();
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Dtos;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityService.Models;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityService.Interfaces;
|
||||
using xIdentityService.Extensions;
|
||||
|
||||
//
|
||||
// TODO: Remove this to xIds ...
|
||||
namespace xIdentityService.Providers
|
||||
{
|
||||
public partial class XAuthorizationProvider // : IXAuthorizationProvider
|
||||
{
|
||||
//
|
||||
// private readonly IXRoleProvider roles;
|
||||
// private readonly IXScopeProvider scopes;
|
||||
// private readonly IXPolicyProvider policies;
|
||||
// private readonly IXAuthorizationCache cache;
|
||||
// private readonly IXRoleHierarchyResolver resolver;
|
||||
|
||||
// public XAuthorizationProvider(
|
||||
// IXRoleProvider roles,
|
||||
// IXScopeProvider scopes,
|
||||
// IXPolicyProvider policies,
|
||||
// IXAuthorizationCache cache,
|
||||
// IXRoleHierarchyResolver resolver
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// this.roles = roles;
|
||||
// this.cache = cache;
|
||||
// this.scopes = scopes;
|
||||
// this.policies = policies;
|
||||
// this.resolver = resolver;
|
||||
// }
|
||||
|
||||
// //
|
||||
// #region Commons ...
|
||||
// /// <summary>
|
||||
// /// Clear Local Cache and Notify other Instances ...
|
||||
// /// </summary>
|
||||
// public async Task InvalidateAsync(string policyName = null)
|
||||
// {
|
||||
// //
|
||||
// if (policyName.IsNullOrEmpty())
|
||||
// {
|
||||
// cache.Clear();
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// cache.RemovePolicy(policyName);
|
||||
// }
|
||||
// }
|
||||
// #endregion
|
||||
|
||||
// //
|
||||
// #region Private ...
|
||||
// private async Task<XRoleDefinitionDto> FindRoleOrThrowAsync(
|
||||
// string name,
|
||||
// CancellationToken cancellationToken
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// if (name.IsNullOrEmpty())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// var normalized = name.ToNormalString();
|
||||
// var result = await roles.FindOneAsync(
|
||||
// predicate: r => r.Name.ToLower() == normalized,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
// if (result.IsNull())
|
||||
// {
|
||||
// XException.NotFound.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// private async Task<XScopeDefinitionDto> FindScopeOrThrowAsync(
|
||||
// string name,
|
||||
// CancellationToken cancellationToken
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// if (name.IsNullOrEmpty())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// var normalized = name.ToNormalString();
|
||||
// var result = await scopes.FindOneAsync(
|
||||
// predicate: s => s.Name.ToLower() == normalized,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
// if (result.IsNull())
|
||||
// {
|
||||
// XException.NotFound.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// private async Task<XPolicyDefinitionDto> FindPolicyOrThrowAsync(
|
||||
// string name,
|
||||
// CancellationToken cancellationToken
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// if (name.IsNullOrEmpty())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// var normalized = name.ToNormalString();
|
||||
// var result = await policies.FindOneAsync(
|
||||
// predicate: p => p.Name.ToLower() == normalized,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
// if (result.IsNull())
|
||||
// {
|
||||
// XException.NotFound.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// private async Task ValidateReferencesAsync(
|
||||
// XPolicyDefinitionDto item,
|
||||
// CancellationToken cancellationToken
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Defensive guard ...
|
||||
// if (item.IsNull())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
// //
|
||||
// // The DTO stores RequiredRoles / RequiredScopes as CSV strings.
|
||||
// // Parse them into collections ONCE (ParseListString NREs on a null
|
||||
// // string, so guard first) ...
|
||||
|
||||
// //
|
||||
// var requiredRoles = item.RequiredRoles.IsNullOrEmpty()
|
||||
// ? []
|
||||
// : item.RequiredRoles.ParseListString<string>().ToList();
|
||||
|
||||
// //
|
||||
// var requiredScopes = item.RequiredScopes.IsNullOrEmpty()
|
||||
// ? []
|
||||
// : item.RequiredScopes.ParseListString<string>().ToList();
|
||||
|
||||
// //
|
||||
// // Referenced Roles must exist ...
|
||||
// if (requiredRoles.HasChild())
|
||||
// {
|
||||
// //
|
||||
// var existingRoles = new HashSet<string>(
|
||||
// (await roles.GetAllAsync(cancellationToken: cancellationToken))
|
||||
// .Select(r => r.Name.ToNormalString()),
|
||||
// StringComparer.OrdinalIgnoreCase
|
||||
// );
|
||||
// if (requiredRoles.Any(r => !existingRoles.Contains(r.ToNormalString())))
|
||||
// {
|
||||
// XException.NotFound.Throw();
|
||||
// }
|
||||
// }
|
||||
|
||||
// //
|
||||
// // Referenced Scopes must exist ...
|
||||
// if (requiredScopes.HasChild())
|
||||
// {
|
||||
// //
|
||||
// var existingScopes = new HashSet<string>(
|
||||
// (await scopes.GetAllAsync(cancellationToken: cancellationToken))
|
||||
// .Select(s => s.Name.ToNormalString()),
|
||||
// StringComparer.OrdinalIgnoreCase
|
||||
// );
|
||||
// if (requiredScopes.Any(s => !existingScopes.Contains(s.ToNormalString())))
|
||||
// {
|
||||
// XException.NotFound.Throw();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// private async Task<XEffectiveAuthorizationDto> ToDtoWithEffectiveRolesAsync(
|
||||
// XPolicyDefinitionDto item,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Null / nameless guard ...
|
||||
// if (item.IsNull() || item.Name.IsNullOrEmpty())
|
||||
// {
|
||||
// return null;
|
||||
// }
|
||||
|
||||
// //
|
||||
// // Parse the DTO's CSV-string RequiredRoles. ParseListString NREs on a
|
||||
// // null string, so guard first; the resolver itself is null-safe on an
|
||||
// // empty explicitRoles set ...
|
||||
// var explicitRoles = item.RequiredRoles.IsNullOrEmpty()
|
||||
// ? null
|
||||
// : item.RequiredRoles.ParseListString<string>();
|
||||
|
||||
// //
|
||||
// // Resolve the effective role set
|
||||
// // (explicit RequiredRoles U roles by MinRoleWeight U parent chain) ...
|
||||
// var effectiveRoles = await resolver.ResolveEffectiveRolesAsync(
|
||||
// explicitRoles: explicitRoles,
|
||||
// minRoleWeight: item.MinRoleWeight,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
|
||||
// //
|
||||
// // Project onto XEffectiveAuthorizationDto - the ONLY DTO that carries
|
||||
// // EffectiveRoles / EffectiveScopes / EffectiveClaims. Each CSV / JSON
|
||||
// // field is null-guarded here (the shared ToEffectiveAuthorization
|
||||
// // extension calls ParseListString on RequiredScopes without a null
|
||||
// // guard, so the projection is built inline to stay null-safe) ...
|
||||
// var result = new XEffectiveAuthorizationDto
|
||||
// {
|
||||
// PolicyName = item.Name,
|
||||
// RequireEnabledUser = item.RequireEnabledUser,
|
||||
// RequireAuthenticatedUser = item.RequireAuthenticatedUser,
|
||||
// EffectiveClaims = item.RequiredClaims.ToRequiredClaims(),
|
||||
// EffectiveScopes = item.RequiredScopes.IsNullOrEmpty()
|
||||
// ? new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||
// : new HashSet<string>(
|
||||
// item.RequiredScopes.ParseListString<string>(),
|
||||
// StringComparer.OrdinalIgnoreCase
|
||||
// ),
|
||||
// EffectiveRoles = effectiveRoles.HasChild()
|
||||
// ? new HashSet<string>(effectiveRoles, StringComparer.OrdinalIgnoreCase)
|
||||
// : new HashSet<string>(StringComparer.OrdinalIgnoreCase),
|
||||
// };
|
||||
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
// #endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using xCommons.Extensions;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityService.Interfaces;
|
||||
|
||||
namespace xIdentityService.Providers
|
||||
{
|
||||
public class XRoleHierarchyResolver : IXRoleHierarchyResolver
|
||||
{
|
||||
private readonly IXRoleProvider provider;
|
||||
|
||||
public XRoleHierarchyResolver(
|
||||
IXRoleProvider provider
|
||||
)
|
||||
{
|
||||
this.provider = provider;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<string>> GetRolesByMinWeightAsync(
|
||||
int minWeight,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var roles = await provider.FindManyAsync(
|
||||
predicate: r => r.IsEnabled && r.Weight >= minWeight,
|
||||
orderBuilder: q => q.OrderBy(r => r.Weight),
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
var result = roles
|
||||
.Select(r => r.Name.ToNormalString())
|
||||
.Distinct()
|
||||
.ToList();
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<string>> ResolveEffectiveRolesAsync(
|
||||
IEnumerable<string> explicitRoles,
|
||||
int? minRoleWeight,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var result = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
|
||||
|
||||
//
|
||||
// Explicit Roles ...
|
||||
if (explicitRoles.HasChild())
|
||||
{
|
||||
//
|
||||
foreach (var role in explicitRoles)
|
||||
{
|
||||
result.Add(role.ToNormalString());
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Roles by Weight ...
|
||||
if (minRoleWeight.HasValue)
|
||||
{
|
||||
//
|
||||
var byWeight = await GetRolesByMinWeightAsync(
|
||||
minRoleWeight.Value,
|
||||
cancellationToken
|
||||
);
|
||||
foreach (var role in byWeight)
|
||||
{
|
||||
result.Add(role);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Parent Chain: any Role whose ParentRoleName is in result inherits it ...
|
||||
var all = await provider.GetAllAsync(cancellationToken: cancellationToken);
|
||||
bool changed;
|
||||
do
|
||||
{
|
||||
//
|
||||
changed = false;
|
||||
foreach (var role in all.Where(r => r.IsEnabled && !r.ParentRoleName.IsNullOrEmpty()))
|
||||
{
|
||||
//
|
||||
if (result.Contains(role.ParentRoleName) &&
|
||||
result.Add(role.Name.ToNormalString()))
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
} while (changed);
|
||||
|
||||
//
|
||||
return [.. result];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,8 +20,7 @@
|
||||
|
||||
<!-- Icon Handling -->
|
||||
<ItemGroup>
|
||||
<None Include="../../Documents/Resources/Images/favicon.png" Link="icon.png" Pack="true"
|
||||
PackagePath="\icon.png" />
|
||||
<None Include="../../Documents/Resources/Images/favicon.png" Link="icon.png" Pack="true" PackagePath="\icon.png" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Local Modules -->
|
||||
@@ -36,9 +35,8 @@
|
||||
|
||||
<!-- Dependencies -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="IdentityModel.AspNetCore.OAuth2Introspection"
|
||||
Version="4.0.0-preview.6" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.Abstractions" Version="2.2.0" />
|
||||
<PackageReference Include="IdentityModel.AspNetCore.OAuth2Introspection" Version="4.0.0-preview.6" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- For XML Documentation Support -->
|
||||
|
||||
Reference in New Issue
Block a user