last ...
This commit is contained in:
+216
-251
@@ -14,280 +14,245 @@ using xIdentityService.Extensions;
|
||||
// TODO: Remove this to xIds ...
|
||||
namespace xIdentityService.Providers
|
||||
{
|
||||
public partial class XAuthorizationProvider : IXAuthorizationProvider
|
||||
public partial class XAuthorizationProvider // : IXAuthorizationProvider
|
||||
{
|
||||
//
|
||||
private readonly IXRoleProvider roles;
|
||||
private readonly IXScopeProvider scopes;
|
||||
private readonly IXPolicyProvider policies;
|
||||
private readonly IXRoleSyncService roleSync;
|
||||
private readonly IXAuthorizationCache cache;
|
||||
private readonly IXScopeSyncService scopeSync;
|
||||
private readonly IXRoleHierarchyResolver resolver;
|
||||
// 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,
|
||||
IXRoleSyncService roleSync,
|
||||
IXAuthorizationCache cache,
|
||||
IXScopeSyncService scopeSync,
|
||||
IXRoleHierarchyResolver resolver
|
||||
)
|
||||
{
|
||||
//
|
||||
this.roles = roles;
|
||||
this.cache = cache;
|
||||
this.scopes = scopes;
|
||||
this.policies = policies;
|
||||
this.roleSync = roleSync;
|
||||
this.resolver = resolver;
|
||||
this.scopeSync = scopeSync;
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
// //
|
||||
// #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
|
||||
|
||||
/// <summary>
|
||||
/// Re-push every Role and Scope into IdentityServer and drop the local
|
||||
/// authorization cache so policies rebuild lazily on next evaluation.
|
||||
/// </summary>
|
||||
public async Task SyncAllAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
//
|
||||
// Sync all Roles to IdentityServer (RoleManager<IdentityRole>) ...
|
||||
foreach (var role in roles.AsQueryable())
|
||||
{
|
||||
//
|
||||
await roleSync
|
||||
.UpsertAsync(role, cancellationToken);
|
||||
}
|
||||
// //
|
||||
// #region Private ...
|
||||
// private async Task<XRoleDefinitionDto> FindRoleOrThrowAsync(
|
||||
// string name,
|
||||
// CancellationToken cancellationToken
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// if (name.IsNullOrEmpty())
|
||||
// {
|
||||
// XException.InvalidArgs.Throw();
|
||||
// }
|
||||
|
||||
//
|
||||
// Sync all Scopes to IdentityServer (ConfigurationDbContext) ...
|
||||
foreach (var scope in scopes.AsQueryable())
|
||||
{
|
||||
//
|
||||
await scopeSync
|
||||
.UpsertAsync(scope, cancellationToken);
|
||||
}
|
||||
// //
|
||||
// var normalized = name.ToNormalString();
|
||||
// var result = await roles.FindOneAsync(
|
||||
// predicate: r => r.Name.ToLower() == normalized,
|
||||
// cancellationToken: cancellationToken
|
||||
// );
|
||||
// if (result.IsNull())
|
||||
// {
|
||||
// XException.NotFound.Throw();
|
||||
// }
|
||||
|
||||
//
|
||||
// Drop local authorization cache ...
|
||||
await InvalidateAsync();
|
||||
}
|
||||
#endregion
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
private async Task<XRoleDefinitionDto> FindRoleOrThrowAsync(
|
||||
string name,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
//
|
||||
if (name.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
// private async Task<XScopeDefinitionDto> FindScopeOrThrowAsync(
|
||||
// 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();
|
||||
}
|
||||
// //
|
||||
// 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;
|
||||
}
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
private async Task<XScopeDefinitionDto> FindScopeOrThrowAsync(
|
||||
string name,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
//
|
||||
if (name.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
// private async Task<XPolicyDefinitionDto> FindPolicyOrThrowAsync(
|
||||
// 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();
|
||||
}
|
||||
// //
|
||||
// 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;
|
||||
}
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
|
||||
private async Task<XPolicyDefinitionDto> FindPolicyOrThrowAsync(
|
||||
string name,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
//
|
||||
if (name.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
// private async Task ValidateReferencesAsync(
|
||||
// XPolicyDefinitionDto item,
|
||||
// CancellationToken cancellationToken
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Defensive guard ...
|
||||
// if (item.IsNull())
|
||||
// {
|
||||
// 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();
|
||||
}
|
||||
// //
|
||||
// // The DTO stores RequiredRoles / RequiredScopes as CSV strings.
|
||||
// // Parse them into collections ONCE (ParseListString NREs on a null
|
||||
// // string, so guard first) ...
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
// //
|
||||
// var requiredRoles = item.RequiredRoles.IsNullOrEmpty()
|
||||
// ? []
|
||||
// : item.RequiredRoles.ParseListString<string>().ToList();
|
||||
|
||||
private async Task ValidateReferencesAsync(
|
||||
XPolicyDefinitionDto item,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
//
|
||||
// Defensive guard ...
|
||||
if (item.IsNull())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
// //
|
||||
// var requiredScopes = item.RequiredScopes.IsNullOrEmpty()
|
||||
// ? []
|
||||
// : item.RequiredScopes.ParseListString<string>().ToList();
|
||||
|
||||
//
|
||||
// The DTO stores RequiredRoles / RequiredScopes as CSV strings.
|
||||
// Parse them into collections ONCE (ParseListString NREs on a null
|
||||
// string, so guard first) ...
|
||||
// //
|
||||
// // 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();
|
||||
// }
|
||||
// }
|
||||
|
||||
//
|
||||
var requiredRoles = item.RequiredRoles.IsNullOrEmpty()
|
||||
? []
|
||||
: item.RequiredRoles.ParseListString<string>().ToList();
|
||||
// //
|
||||
// // 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();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
//
|
||||
var requiredScopes = item.RequiredScopes.IsNullOrEmpty()
|
||||
? []
|
||||
: item.RequiredScopes.ParseListString<string>().ToList();
|
||||
// private async Task<XEffectiveAuthorizationDto> ToDtoWithEffectiveRolesAsync(
|
||||
// XPolicyDefinitionDto item,
|
||||
// CancellationToken cancellationToken = default
|
||||
// )
|
||||
// {
|
||||
// //
|
||||
// // Null / nameless guard ...
|
||||
// if (item.IsNull() || item.Name.IsNullOrEmpty())
|
||||
// {
|
||||
// return null;
|
||||
// }
|
||||
|
||||
//
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
// //
|
||||
// // 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>();
|
||||
|
||||
//
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
// //
|
||||
// // 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
|
||||
// );
|
||||
|
||||
private async Task<XEffectiveAuthorizationDto> ToDtoWithEffectiveRolesAsync(
|
||||
XPolicyDefinitionDto item,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Null / nameless guard ...
|
||||
if (item.IsNull() || item.Name.IsNullOrEmpty())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
// //
|
||||
// // 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),
|
||||
// };
|
||||
|
||||
//
|
||||
// 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
|
||||
// //
|
||||
// return result;
|
||||
// }
|
||||
// #endregion
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
using xCommons.Extensions;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityService.Interfaces;
|
||||
using xIdentityService.Extensions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace xIdentityService.Providers
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolve Policies from Cache → Repository → Default (static) Provider ...
|
||||
/// </summary>
|
||||
public class XDynamicPolicyProvider : IAuthorizationPolicyProvider
|
||||
{
|
||||
private readonly IXAuthorizationCache cache;
|
||||
private readonly IServiceScopeFactory scopeFactory;
|
||||
private readonly DefaultAuthorizationPolicyProvider fallback;
|
||||
|
||||
public XDynamicPolicyProvider(
|
||||
IXAuthorizationCache cache,
|
||||
IServiceScopeFactory scopeFactory,
|
||||
IOptions<AuthorizationOptions> options
|
||||
)
|
||||
{
|
||||
//
|
||||
this.cache = cache;
|
||||
this.scopeFactory = scopeFactory;
|
||||
fallback = new DefaultAuthorizationPolicyProvider(options);
|
||||
}
|
||||
|
||||
public Task<AuthorizationPolicy> GetDefaultPolicyAsync() =>
|
||||
fallback.GetDefaultPolicyAsync();
|
||||
|
||||
public async Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
|
||||
{
|
||||
//
|
||||
if (policyName.IsNullOrEmpty())
|
||||
{
|
||||
return await fallback.GetPolicyAsync(policyName);
|
||||
}
|
||||
|
||||
//
|
||||
// 1. Cache ...
|
||||
if (cache.TryGetPolicy(policyName, out var cached))
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
|
||||
//
|
||||
// 2. Repository (needs a Scope because Provider is Singleton) ...
|
||||
using (var scope = scopeFactory.CreateScope())
|
||||
{
|
||||
//
|
||||
var repository = scope.ServiceProvider.GetService<IXPolicyProvider>();
|
||||
var resolver = scope.ServiceProvider.GetService<IXRoleHierarchyResolver>();
|
||||
|
||||
//
|
||||
if (!repository.IsNull() && !resolver.IsNull())
|
||||
{
|
||||
//
|
||||
var normalized = policyName.ToNormalString();
|
||||
var definition = await repository.FindOneAsync(
|
||||
predicate: p => p.IsEnabled && p.Name.ToLower() == normalized
|
||||
);
|
||||
|
||||
//
|
||||
var requiredRoles = definition.RequiredRoles
|
||||
.ParseListString<string>();
|
||||
if (!definition.IsNull())
|
||||
{
|
||||
//
|
||||
var roles = await resolver.ResolveEffectiveRolesAsync(
|
||||
explicitRoles: requiredRoles,
|
||||
minRoleWeight: definition.MinRoleWeight
|
||||
);
|
||||
|
||||
//
|
||||
var policy = definition.ToAuthorizationPolicy(roles);
|
||||
if (!policy.IsNull())
|
||||
{
|
||||
cache.SetPolicy(policyName, policy);
|
||||
return policy;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// 3. Fallback to Static Policies (LocalApi.PolicyName, XPolicies.*) ...
|
||||
return await fallback.GetPolicyAsync(policyName);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user