This commit is contained in:
2026-11-26 19:36:49 +03:30
parent 4e114aa85a
commit bdc8791822
8 changed files with 752 additions and 921 deletions
+9 -9
View File
@@ -1,6 +1,8 @@
using System; using System;
using xCommons.Extensions; using xCommons.Extensions;
using xExceptions.Constants;
using xCommons.Authorization; using xCommons.Authorization;
using xHttpService.Interfaces;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using xIdentityService.Security; using xIdentityService.Security;
using xIdentityService.Constants; using xIdentityService.Constants;
@@ -12,8 +14,6 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using IdentityModel.AspNetCore.OAuth2Introspection; using IdentityModel.AspNetCore.OAuth2Introspection;
using xHttpService.Interfaces;
using xExceptions.Constants;
namespace xIdentityService.DI namespace xIdentityService.DI
{ {
@@ -150,21 +150,21 @@ namespace xIdentityService.DI
var roles = source.GetRegisteredService<IXRoleProvider>(); var roles = source.GetRegisteredService<IXRoleProvider>();
var scopes = source.GetRegisteredService<IXScopeProvider>(); var scopes = source.GetRegisteredService<IXScopeProvider>();
var policies = source.GetRegisteredService<IXPolicyProvider>(); var policies = source.GetRegisteredService<IXPolicyProvider>();
var roleSync = source.GetRegisteredService<IXRoleSyncService>();
var cache = source.GetRegisteredService<IXAuthorizationCache>(); var cache = source.GetRegisteredService<IXAuthorizationCache>();
var scopeSync = source.GetRegisteredService<IXScopeSyncService>();
var resolver = source.GetRegisteredService<IXRoleHierarchyResolver>(); var resolver = source.GetRegisteredService<IXRoleHierarchyResolver>();
// var roleSync = source.GetRegisteredService<IXRoleSyncService>();
// var scopeSync = source.GetRegisteredService<IXScopeSyncService>();
// //
var isValid = var isInvalid =
roles.IsNull() || roles.IsNull() ||
cache.IsNull() || cache.IsNull() ||
scopes.IsNull() || scopes.IsNull() ||
policies.IsNull() || policies.IsNull() ||
roleSync.IsNull() || resolver.IsNull();
resolver.IsNull() || // roleSync.IsNull() ||
scopeSync.IsNull(); // scopeSync.IsNull();
if (!isValid) if (isInvalid)
{ {
XException.InvalidConfiguration.Throw(); XException.InvalidConfiguration.Throw();
} }
-1
View File
@@ -108,7 +108,6 @@ namespace xIdentityService.Interfaces
// //
#region Utilities ... #region Utilities ...
Task SyncAllAsync(CancellationToken cancellationToken = default);
Task InvalidateAsync(string policyName = null); Task InvalidateAsync(string policyName = null);
#endregion #endregion
} }
-49
View File
@@ -1,49 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
/// <summary>
/// Implemented on xIds over IdentityServer4 ConfigurationDbContext ...
/// </summary>
public interface IXScopeSyncService
{
Task UpsertAsync(
XScopeDefinition scope,
CancellationToken cancellationToken = default
);
Task RemoveAsync(
string scopeName,
CancellationToken cancellationToken = default
);
Task<bool> IsApiResourceExistsAsync(
string apiResourceName,
CancellationToken cancellationToken = default
);
}
/// <summary>
/// Implemented on xIds over RoleManager&lt;IdentityRole&gt; ...
/// </summary>
public interface IXRoleSyncService
{
Task UpsertAsync(
XRoleDefinition role,
CancellationToken cancellationToken = default
);
Task RemoveAsync(
string roleName,
CancellationToken cancellationToken = default
);
Task<int> CountUsersInRoleAsync(
string roleName,
CancellationToken cancellationToken = default
);
Task<IEnumerable<string>> GetUserRolesAsync(
string userSelectByParam,
CancellationToken cancellationToken = default
);
}
}
+243 -233
View File
@@ -15,273 +15,283 @@ namespace xIdentityService.Providers
{ {
public partial class XAuthorizationProvider public partial class XAuthorizationProvider
{ {
// // //
#region Policy ... // #region Policy ...
public async Task<XPolicyDefinitionDto> AddPolicyAsync( // public async Task<XPolicyDefinitionDto> AddPolicyAsync(
XPolicyDefinitionDto item, // XPolicyDefinitionDto item,
XUserClaimsInfoDto userInfo, // XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
// Validate ... // // Validate ...
if (item.IsNull() || item.Name.IsNullOrEmpty()) // if (item.IsNull() || item.Name.IsNullOrEmpty())
{ // {
XException.InvalidArgs.Throw(); // XException.InvalidArgs.Throw();
} // }
// // //
var normalized = item.Name.ToNormalString(); // var normalized = item.Name.ToNormalString();
var exists = await policies.FindOneAsync( // var exists = await policies.FindOneAsync(
predicate: p => p.Name.ToLower() == normalized, // predicate: p => p.Name.ToLower() == normalized,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
if (!exists.IsNull()) // if (!exists.IsNull())
{ // {
XException.Duplicate.Throw(); // XException.Duplicate.Throw();
} // }
// // //
await ValidateReferencesAsync(item, cancellationToken); // await ValidateReferencesAsync(item, cancellationToken);
// // //
item.IsSystem = false; // item.IsSystem = false;
// // //
var result = await policies.AddAsync( // var result = await policies.AddAsync(
item: item, // item: item,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
// // //
await InvalidateAsync(result.Name); // await InvalidateAsync(result.Name);
// // //
return result; // return result;
} // }
public async Task<bool> RemovePolicyAsync( // public async Task<bool> RemovePolicyAsync(
string name, // string name,
XUserClaimsInfoDto userInfo, // XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
var entity = await FindPolicyOrThrowAsync(name, cancellationToken); // var entity = await FindPolicyOrThrowAsync(name, cancellationToken);
if (entity.IsSystem) // if (entity.IsSystem)
{ // {
XException.NotAllowed.Throw(); // XException.NotAllowed.Throw();
} // }
// // //
await policies.RemoveAsync( // await policies.RemoveAsync(
id: entity.Id, // id: entity.Id,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
// // //
await InvalidateAsync(entity.Name); // await InvalidateAsync(entity.Name);
return true; // return true;
} // }
public async Task<XQueryResult<XPolicyDefinitionDto>> QueryPoliciesAsync( // public async Task<XQueryResult<XPolicyDefinitionDto>> QueryPoliciesAsync(
XQuery query, // XQuery query,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
// Validate ... // // Validate ...
if (query.IsNull()) // if (query.IsNull())
{ // {
XException.InvalidArgs.Throw(); // XException.InvalidArgs.Throw();
} // }
// // //
var result = await policies.QueryAsync( // var result = await policies.QueryAsync(
query: query, // query: query,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
// // //
return result; // return result;
} // }
public async Task<XPolicyDefinitionDto> GetPolicyAsync( // public async Task<XPolicyDefinitionDto> GetPolicyAsync(
string name, // string name,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
var result = await FindPolicyOrThrowAsync(name, cancellationToken); // var result = await FindPolicyOrThrowAsync(name, cancellationToken);
// // //
return result; // return result;
} // }
public async Task<XPolicyDefinitionDto> UpdatePolicyAsync( // public async Task<XPolicyDefinitionDto> UpdatePolicyAsync(
string name, // string name,
XPolicyDefinitionDto item, // XPolicyDefinitionDto item,
XUserClaimsInfoDto userInfo, // XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
// Validate ... // // Validate ...
if (name.IsNullOrEmpty() || item.IsNull()) // if (name.IsNullOrEmpty() || item.IsNull())
{ // {
XException.InvalidArgs.Throw(); // XException.InvalidArgs.Throw();
} // }
// // //
var exists = await FindPolicyOrThrowAsync(name, cancellationToken); // var exists = await FindPolicyOrThrowAsync(name, cancellationToken);
if (exists.IsSystem) // if (exists.IsSystem)
{ // {
XException.NotAllowed.Throw(); // XException.NotAllowed.Throw();
} // }
// // //
// Referenced Roles & Scopes must exist ... // // Referenced Roles & Scopes must exist ...
await ValidateReferencesAsync(item, cancellationToken); // await ValidateReferencesAsync(item, cancellationToken);
// // //
var result = await policies.UpdateAsync( // var result = await policies.UpdateAsync(
item: item, // item: item,
id: exists.Id, // id: exists.Id,
userInfo: userInfo, // userInfo: userInfo,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
// // //
// Drop the cached policy so it rebuilds on next evaluation ... // // Drop the cached policy so it rebuilds on next evaluation ...
await InvalidateAsync(result.Name); // await InvalidateAsync(result.Name);
// // //
// Return the updated DTO as-is (EffectiveRoles is not a field on // // Return the updated DTO as-is (EffectiveRoles is not a field on
// XPolicyDefinitionDto) ... // // XPolicyDefinitionDto) ...
return result; // return result;
} // }
public async Task<XPolicyEvaluationResultDto> EvaluatePolicyAsync( // public async Task<XPolicyEvaluationResultDto> EvaluatePolicyAsync(
string name, // string name,
XUserClaimsInfoDto target, // XUserClaimsInfoDto target,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
// Load the policy (throws NotFound when missing) ... // // Load the policy (throws NotFound when missing) ...
var dto = await FindPolicyOrThrowAsync(name, cancellationToken); // var dto = await FindPolicyOrThrowAsync(name, cancellationToken);
// // //
var result = new XPolicyEvaluationResultDto // var result = new XPolicyEvaluationResultDto
{ // {
Passed = true, // Passed = true,
Policy = dto.Name, // Policy = dto.Name,
FailedRequirements = [] // FailedRequirements = []
}; // };
// // //
// Build the policy's effective authorization via the shared helper // // Build the policy's effective authorization via the shared helper
// (resolver + projection onto XEffectiveAuthorizationDto) ... // // (resolver + projection onto XEffectiveAuthorizationDto) ...
var auth = await ToDtoWithEffectiveRolesAsync(dto, cancellationToken); // var auth = await ToDtoWithEffectiveRolesAsync(dto, cancellationToken);
if (auth.IsNull()) // if (auth.IsNull())
{ // {
// // //
result.Passed = false; // result.Passed = false;
result.FailedRequirements.Add("PolicyNotBuilt"); // result.FailedRequirements.Add("PolicyNotBuilt");
// // //
return result; // return result;
} // }
// // //
// Anonymous user fails any policy that requires authentication ... // // Anonymous user fails any policy that requires authentication ...
if (target.IsNull()) // if (target.IsNull())
{ // {
// // //
if (auth.RequireAuthenticatedUser) // if (auth.RequireAuthenticatedUser)
{ // {
result.Passed = false; // //
result.FailedRequirements.Add("RequireAuthenticatedUser"); // result.Passed = false;
} // result.FailedRequirements.Add("RequireAuthenticatedUser");
// }
// // //
return result; // return result;
} // }
// // //
// Effective Roles: the user must hold at least one ... // // Effective Roles: the user must hold at least one ...
if (auth.EffectiveRoles.HasChild()) // if (auth.EffectiveRoles.HasChild())
{ // {
// // //
var userRoles = await roleSync.GetUserRolesAsync( // // var userRoles = await roles.FindManyAsync(
target.GetUserSelectByParam(), // // target.GetUserSelectByParam(),
cancellationToken // // cancellationToken
); // // );
// // //
var matched = auth.EffectiveRoles.Any(er => // var userSelectByParam = target.GetUserSelectByParam();
userRoles.Any(ur =>
string.Equals(ur, er, StringComparison.OrdinalIgnoreCase)
)
);
// // //
if (!matched) // var userRoles = await roles.FindManyAsync(
{ // predicate: x => x.
// // cancellationToken: cancellationToken
result.Passed = false; // );
result.FailedRequirements.Add("RequiredRoles");
}
}
// // //
// NOTE: RequireEnabledUser (IsEnabled / !IsBanned), EffectiveScopes and // var matched = auth.EffectiveRoles.Any(er =>
// EffectiveClaims checks are layered on here once the matching flags / // userRoles.Any(ur =>
// collections on XUserClaimsInfoDto (xIdentityModels) are wired. // string.Equals(ur, er, StringComparison.OrdinalIgnoreCase)
return result; // )
} // );
public async Task<XEffectiveAuthorizationDto> GetEffectiveAuthorizationAsync( // //
XUserClaimsInfoDto target, // if (!matched)
CancellationToken cancellationToken = default // {
) // //
{ // result.Passed = false;
// // result.FailedRequirements.Add("RequiredRoles");
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()) // // NOTE: RequireEnabledUser (IsEnabled / !IsBanned), EffectiveScopes and
{ // // EffectiveClaims checks are layered on here once the matching flags /
return result; // // collections on XUserClaimsInfoDto (xIdentityModels) are wired.
} // return result;
// }
// // public async Task<XEffectiveAuthorizationDto> GetEffectiveAuthorizationAsync(
// Effective roles = the user's actual roles (from RoleManager) ... // XUserClaimsInfoDto target,
var userRoles = await roleSync.GetUserRolesAsync( // CancellationToken cancellationToken = default
cancellationToken: cancellationToken, // )
userSelectByParam: target.GetUserSelectByParam() // {
); // //
foreach (var role in userRoles) // var result = new XEffectiveAuthorizationDto
{ // {
result.EffectiveRoles.Add(role); // RequireEnabledUser = !target.IsNull(),
} // RequireAuthenticatedUser = !target.IsNull(),
// EffectiveClaims = new List<XRequiredClaimDto>(),
// EffectiveRoles = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
// EffectiveScopes = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
// };
// // //
// NOTE: EffectiveScopes / EffectiveClaims aggregation is wired here from // if (target.IsNull())
// the user's scope / claim source on XUserClaimsInfoDto (xIdentityModels). // {
return result; // return result;
} // }
#endregion
// // //
#region Private ... // // Effective roles = the user's actual roles (from RoleManager) ...
#endregion // 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
} }
} }
+145 -145
View File
@@ -12,170 +12,170 @@ namespace xIdentityService.Providers
public partial class XAuthorizationProvider public partial class XAuthorizationProvider
{ {
// //
#region Role ... // #region Role ...
public async Task<IEnumerable<XRoleDefinitionDto>> GetRolesAsync( // public async Task<IEnumerable<XRoleDefinitionDto>> GetRolesAsync(
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
var result = await roles // var result = await roles
.GetAllAsync(cancellationToken: cancellationToken); // .GetAllAsync(cancellationToken: cancellationToken);
// // //
return result; // return result;
} // }
public async Task<XRoleDefinitionDto> GetRoleAsync( // public async Task<XRoleDefinitionDto> GetRoleAsync(
string name, // string name,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
var result = await FindRoleOrThrowAsync(name, cancellationToken); // var result = await FindRoleOrThrowAsync(name, cancellationToken);
// // //
return result; // return result;
} // }
public async Task<XRoleDefinitionDto> AddRoleAsync( // public async Task<XRoleDefinitionDto> AddRoleAsync(
XRoleDefinitionDto item, // XRoleDefinitionDto item,
XUserClaimsInfoDto userInfo, // XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
// Validate ... // // Validate ...
if (item.IsNull() || item.Name.IsNullOrEmpty()) // if (item.IsNull() || item.Name.IsNullOrEmpty())
{ // {
XException.InvalidArgs.Throw(); // XException.InvalidArgs.Throw();
} // }
// // //
// Duplicate check ... // // Duplicate check ...
var normalized = item.Name.ToNormalString(); // var normalized = item.Name.ToNormalString();
var exists = await roles.FindOneAsync( // var exists = await roles.FindOneAsync(
predicate: r => r.Name.ToLower() == normalized, // predicate: r => r.Name.ToLower() == normalized,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
if (!exists.IsNull()) // if (!exists.IsNull())
{ // {
XException.Duplicate.Throw(); // XException.Duplicate.Throw();
} // }
// // //
// Persist ... // // Persist ...
item.IsSystem = false; // item.IsSystem = false;
var result = await roles.AddAsync( // var result = await roles.AddAsync(
item: item, // item: item,
userInfo: userInfo, // userInfo: userInfo,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
// // //
// Sync to IdentityServer (RoleManager<IdentityRole>) ... // // Sync to IdentityServer (RoleManager<IdentityRole>) ...
var entity = roles.AsQueryable() // var entity = roles.AsQueryable()
.FirstOrDefault(r => r.Name.ToLower() == normalized); // .FirstOrDefault(r => r.Name.ToLower() == normalized);
if (!entity.IsNull()) // if (!entity.IsNull())
{ // {
await roleSync.UpsertAsync(entity, cancellationToken); // await roleSync.UpsertAsync(entity, cancellationToken);
} // }
// // //
await InvalidateAsync(); // await InvalidateAsync();
return result; // return result;
} // }
public async Task<XRoleDefinitionDto> UpdateRoleAsync( // public async Task<XRoleDefinitionDto> UpdateRoleAsync(
string name, // string name,
XRoleDefinitionDto item, // XRoleDefinitionDto item,
XUserClaimsInfoDto userInfo, // XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
// Validate ... // // Validate ...
if (name.IsNullOrEmpty() || item.IsNull()) // if (name.IsNullOrEmpty() || item.IsNull())
{ // {
XException.InvalidArgs.Throw(); // XException.InvalidArgs.Throw();
} // }
// // //
var existing = await FindRoleOrThrowAsync(name, cancellationToken); // var existing = await FindRoleOrThrowAsync(name, cancellationToken);
if (existing.IsSystem) // if (existing.IsSystem)
{ // {
XException.NotAllowed.Throw(); // XException.NotAllowed.Throw();
} // }
// // //
var updated = await roles.UpdateAsync( // var updated = await roles.UpdateAsync(
id: existing.Id, // id: existing.Id,
item: item, // item: item,
userInfo: userInfo, // userInfo: userInfo,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
// // //
// Sync to IdentityServer ... // // Sync to IdentityServer ...
var entity = roles.AsQueryable() // var entity = roles.AsQueryable()
.FirstOrDefault(r => r.Name.ToLower() == name.ToNormalString()); // .FirstOrDefault(r => r.Name.ToLower() == name.ToNormalString());
if (!entity.IsNull()) // if (!entity.IsNull())
{ // {
await roleSync.UpsertAsync(entity, cancellationToken); // await roleSync.UpsertAsync(entity, cancellationToken);
} // }
// // //
await InvalidateAsync(); // await InvalidateAsync();
return updated; // return updated;
} // }
public async Task<bool> RemoveRoleAsync( // public async Task<bool> RemoveRoleAsync(
string name, // string name,
XUserClaimsInfoDto userInfo, // XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
var exists = await FindRoleOrThrowAsync(name, cancellationToken); // var exists = await FindRoleOrThrowAsync(name, cancellationToken);
if (exists.IsSystem) // if (exists.IsSystem)
{ // {
XException.NotAllowed.Throw(); // XException.NotAllowed.Throw();
} // }
// // //
await roles.RemoveAsync( // await roles.RemoveAsync(
id: exists.Id, // id: exists.Id,
userInfo: userInfo, // userInfo: userInfo,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
// // //
// Remove from IdentityServer ... // // Remove from IdentityServer ...
await roleSync.RemoveAsync(name, cancellationToken); // await roleSync.RemoveAsync(name, cancellationToken);
// // //
await InvalidateAsync(); // await InvalidateAsync();
return true; // return true;
} // }
public async Task<int> CountUsersInRoleAsync( // public async Task<int> CountUsersInRoleAsync(
string name, // string name,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
// Fail fast if the role itself does not exist ... // // Fail fast if the role itself does not exist ...
await FindRoleOrThrowAsync(name, cancellationToken); // await FindRoleOrThrowAsync(name, cancellationToken);
// // //
var result = await roleSync // var result = await roleSync
.CountUsersInRoleAsync( // .CountUsersInRoleAsync(
name, // name,
cancellationToken // cancellationToken
); // );
// // //
return result; // return result;
} // }
#endregion // #endregion
} }
} }
+139 -139
View File
@@ -13,162 +13,162 @@ namespace xIdentityService.Providers
{ {
public partial class XAuthorizationProvider public partial class XAuthorizationProvider
{ {
// // //
#region Scope ... // #region Scope ...
public async Task<XQueryResult<XScopeDefinitionDto>> QueryScopesAsync( // public async Task<XQueryResult<XScopeDefinitionDto>> QueryScopesAsync(
XQuery query, // XQuery query,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
if (query.IsNull()) // if (query.IsNull())
{ // {
XException.InvalidArgs.Throw(); // XException.InvalidArgs.Throw();
} // }
// // //
var result = await scopes.QueryAsync( // var result = await scopes.QueryAsync(
query: query, // query: query,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
// // //
return result; // return result;
} // }
public async Task<XScopeDefinitionDto> GetScopeAsync( // public async Task<XScopeDefinitionDto> GetScopeAsync(
string name, // string name,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
var result = await FindScopeOrThrowAsync(name, cancellationToken); // var result = await FindScopeOrThrowAsync(name, cancellationToken);
// // //
return result; // return result;
} // }
public async Task<XScopeDefinitionDto> AddScopeAsync( // public async Task<XScopeDefinitionDto> AddScopeAsync(
XScopeDefinitionDto item, // XScopeDefinitionDto item,
XUserClaimsInfoDto userInfo, // XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
// Validate ... // // Validate ...
if (item.IsNull() || item.Name.IsNullOrEmpty()) // if (item.IsNull() || item.Name.IsNullOrEmpty())
{ // {
XException.InvalidArgs.Throw(); // XException.InvalidArgs.Throw();
} // }
// // //
// Duplicate check ... // // Duplicate check ...
var normalized = item.Name.ToNormalString(); // var normalized = item.Name.ToNormalString();
var exists = await scopes.FindOneAsync( // var exists = await scopes.FindOneAsync(
cancellationToken: cancellationToken, // cancellationToken: cancellationToken,
predicate: s => s.Name.ToLower() == normalized // predicate: s => s.Name.ToLower() == normalized
); // );
if (!exists.IsNull()) // if (!exists.IsNull())
{ // {
XException.Duplicate.Throw(); // XException.Duplicate.Throw();
} // }
// // //
// Persist ... // // Persist ...
item.IsSystem = false; // item.IsSystem = false;
var result = await scopes.AddAsync( // var result = await scopes.AddAsync(
item: item, // item: item,
userInfo: userInfo, // userInfo: userInfo,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
// // //
// Sync to IdentityServer (ConfigurationDbContext) ... // // Sync to IdentityServer (ConfigurationDbContext) ...
var entity = scopes.AsQueryable() // var entity = scopes.AsQueryable()
.FirstOrDefault(s => s.Name.ToLower() == normalized); // .FirstOrDefault(s => s.Name.ToLower() == normalized);
if (!entity.IsNull()) // if (!entity.IsNull())
{ // {
// // //
await scopeSync // await scopeSync
.UpsertAsync(entity, cancellationToken); // .UpsertAsync(entity, cancellationToken);
} // }
// // //
await InvalidateAsync(); // await InvalidateAsync();
return result; // return result;
} // }
public async Task<XScopeDefinitionDto> UpdateScopeAsync( // public async Task<XScopeDefinitionDto> UpdateScopeAsync(
string name, // string name,
XScopeDefinitionDto item, // XScopeDefinitionDto item,
XUserClaimsInfoDto userInfo, // XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
// Validate ... // // Validate ...
if (name.IsNullOrEmpty() || item.IsNull()) // if (name.IsNullOrEmpty() || item.IsNull())
{ // {
XException.InvalidArgs.Throw(); // XException.InvalidArgs.Throw();
} // }
// // //
var existing = await FindScopeOrThrowAsync(name, cancellationToken); // var existing = await FindScopeOrThrowAsync(name, cancellationToken);
if (existing.IsSystem) // if (existing.IsSystem)
{ // {
XException.NotAllowed.Throw(); // XException.NotAllowed.Throw();
} // }
// // //
var updated = await scopes.UpdateAsync( // var updated = await scopes.UpdateAsync(
id: existing.Id, // id: existing.Id,
item: item, // item: item,
userInfo: userInfo, // userInfo: userInfo,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
// // //
// Sync to IdentityServer ... // // Sync to IdentityServer ...
var entity = scopes.AsQueryable() // var entity = scopes.AsQueryable()
.FirstOrDefault(s => s.Name.ToLower() == name.ToNormalString()); // .FirstOrDefault(s => s.Name.ToLower() == name.ToNormalString());
if (!entity.IsNull()) // if (!entity.IsNull())
{ // {
await scopeSync.UpsertAsync(entity, cancellationToken); // await scopeSync.UpsertAsync(entity, cancellationToken);
} // }
// // //
await InvalidateAsync(); // await InvalidateAsync();
return updated; // return updated;
} // }
public async Task<bool> RemoveScopeAsync( // public async Task<bool> RemoveScopeAsync(
string name, // string name,
XUserClaimsInfoDto userInfo, // XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default // CancellationToken cancellationToken = default
) // )
{ // {
// // //
var entity = await FindScopeOrThrowAsync(name, cancellationToken); // var entity = await FindScopeOrThrowAsync(name, cancellationToken);
if (entity.IsSystem) // if (entity.IsSystem)
{ // {
XException.NotAllowed.Throw(); // XException.NotAllowed.Throw();
} // }
// // //
await scopes.RemoveAsync( // await scopes.RemoveAsync(
id: entity.Id, // id: entity.Id,
userInfo: userInfo, // userInfo: userInfo,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
// // //
// Remove from IdentityServer ... // // Remove from IdentityServer ...
await scopeSync.RemoveAsync(name, cancellationToken); // await scopeSync.RemoveAsync(name, cancellationToken);
// // //
await InvalidateAsync(); // await InvalidateAsync();
return true; // return true;
} // }
#endregion // #endregion
} }
} }
+216 -251
View File
@@ -14,280 +14,245 @@ using xIdentityService.Extensions;
// TODO: Remove this to xIds ... // TODO: Remove this to xIds ...
namespace xIdentityService.Providers namespace xIdentityService.Providers
{ {
public partial class XAuthorizationProvider : IXAuthorizationProvider public partial class XAuthorizationProvider // : IXAuthorizationProvider
{ {
// //
private readonly IXRoleProvider roles; // private readonly IXRoleProvider roles;
private readonly IXScopeProvider scopes; // private readonly IXScopeProvider scopes;
private readonly IXPolicyProvider policies; // private readonly IXPolicyProvider policies;
private readonly IXRoleSyncService roleSync; // private readonly IXAuthorizationCache cache;
private readonly IXAuthorizationCache cache; // private readonly IXRoleHierarchyResolver resolver;
private readonly IXScopeSyncService scopeSync;
private readonly IXRoleHierarchyResolver resolver;
public XAuthorizationProvider( // public XAuthorizationProvider(
IXRoleProvider roles, // IXRoleProvider roles,
IXScopeProvider scopes, // IXScopeProvider scopes,
IXPolicyProvider policies, // IXPolicyProvider policies,
IXRoleSyncService roleSync, // IXAuthorizationCache cache,
IXAuthorizationCache cache, // IXRoleHierarchyResolver resolver
IXScopeSyncService scopeSync, // )
IXRoleHierarchyResolver resolver // {
) // //
{ // this.roles = roles;
// // this.cache = cache;
this.roles = roles; // this.scopes = scopes;
this.cache = cache; // this.policies = policies;
this.scopes = scopes; // this.resolver = resolver;
this.policies = policies; // }
this.roleSync = roleSync;
this.resolver = resolver;
this.scopeSync = scopeSync;
}
// // //
#region Commons ... // #region Commons ...
/// <summary> // /// <summary>
/// Clear Local Cache and Notify other Instances ... // /// Clear Local Cache and Notify other Instances ...
/// </summary> // /// </summary>
public async Task InvalidateAsync(string policyName = null) // public async Task InvalidateAsync(string policyName = null)
{ // {
// // //
if (policyName.IsNullOrEmpty()) // if (policyName.IsNullOrEmpty())
{ // {
cache.Clear(); // cache.Clear();
} // }
else // else
{ // {
cache.RemovePolicy(policyName); // cache.RemovePolicy(policyName);
} // }
} // }
// #endregion
/// <summary> // //
/// Re-push every Role and Scope into IdentityServer and drop the local // #region Private ...
/// authorization cache so policies rebuild lazily on next evaluation. // private async Task<XRoleDefinitionDto> FindRoleOrThrowAsync(
/// </summary> // string name,
public async Task SyncAllAsync(CancellationToken cancellationToken = default) // CancellationToken cancellationToken
{ // )
// // {
// Sync all Roles to IdentityServer (RoleManager<IdentityRole>) ... // //
foreach (var role in roles.AsQueryable()) // if (name.IsNullOrEmpty())
{ // {
// // XException.InvalidArgs.Throw();
await roleSync // }
.UpsertAsync(role, cancellationToken);
}
// // //
// Sync all Scopes to IdentityServer (ConfigurationDbContext) ... // var normalized = name.ToNormalString();
foreach (var scope in scopes.AsQueryable()) // var result = await roles.FindOneAsync(
{ // predicate: r => r.Name.ToLower() == normalized,
// // cancellationToken: cancellationToken
await scopeSync // );
.UpsertAsync(scope, cancellationToken); // if (result.IsNull())
} // {
// XException.NotFound.Throw();
// }
// // //
// Drop local authorization cache ... // return result;
await InvalidateAsync(); // }
}
#endregion
// // private async Task<XScopeDefinitionDto> FindScopeOrThrowAsync(
#region Private ... // string name,
private async Task<XRoleDefinitionDto> FindRoleOrThrowAsync( // CancellationToken cancellationToken
string name, // )
CancellationToken cancellationToken // {
) // //
{ // if (name.IsNullOrEmpty())
// // {
if (name.IsNullOrEmpty()) // XException.InvalidArgs.Throw();
{ // }
XException.InvalidArgs.Throw();
}
// // //
var normalized = name.ToNormalString(); // var normalized = name.ToNormalString();
var result = await roles.FindOneAsync( // var result = await scopes.FindOneAsync(
predicate: r => r.Name.ToLower() == normalized, // predicate: s => s.Name.ToLower() == normalized,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
if (result.IsNull()) // if (result.IsNull())
{ // {
XException.NotFound.Throw(); // XException.NotFound.Throw();
} // }
// // //
return result; // return result;
} // }
private async Task<XScopeDefinitionDto> FindScopeOrThrowAsync( // private async Task<XPolicyDefinitionDto> FindPolicyOrThrowAsync(
string name, // string name,
CancellationToken cancellationToken // CancellationToken cancellationToken
) // )
{ // {
// // //
if (name.IsNullOrEmpty()) // if (name.IsNullOrEmpty())
{ // {
XException.InvalidArgs.Throw(); // XException.InvalidArgs.Throw();
} // }
// // //
var normalized = name.ToNormalString(); // var normalized = name.ToNormalString();
var result = await scopes.FindOneAsync( // var result = await policies.FindOneAsync(
predicate: s => s.Name.ToLower() == normalized, // predicate: p => p.Name.ToLower() == normalized,
cancellationToken: cancellationToken // cancellationToken: cancellationToken
); // );
if (result.IsNull()) // if (result.IsNull())
{ // {
XException.NotFound.Throw(); // XException.NotFound.Throw();
} // }
// // //
return result; // return result;
} // }
private async Task<XPolicyDefinitionDto> FindPolicyOrThrowAsync( // private async Task ValidateReferencesAsync(
string name, // XPolicyDefinitionDto item,
CancellationToken cancellationToken // CancellationToken cancellationToken
) // )
{ // {
// // //
if (name.IsNullOrEmpty()) // // Defensive guard ...
{ // if (item.IsNull())
XException.InvalidArgs.Throw(); // {
} // XException.InvalidArgs.Throw();
// }
// // //
var normalized = name.ToNormalString(); // // The DTO stores RequiredRoles / RequiredScopes as CSV strings.
var result = await policies.FindOneAsync( // // Parse them into collections ONCE (ParseListString NREs on a null
predicate: p => p.Name.ToLower() == normalized, // // string, so guard first) ...
cancellationToken: cancellationToken
);
if (result.IsNull())
{
XException.NotFound.Throw();
}
// // //
return result; // var requiredRoles = item.RequiredRoles.IsNullOrEmpty()
} // ? []
// : item.RequiredRoles.ParseListString<string>().ToList();
private async Task ValidateReferencesAsync( // //
XPolicyDefinitionDto item, // var requiredScopes = item.RequiredScopes.IsNullOrEmpty()
CancellationToken cancellationToken // ? []
) // : item.RequiredScopes.ParseListString<string>().ToList();
{
//
// Defensive guard ...
if (item.IsNull())
{
XException.InvalidArgs.Throw();
}
// // //
// The DTO stores RequiredRoles / RequiredScopes as CSV strings. // // Referenced Roles must exist ...
// Parse them into collections ONCE (ParseListString NREs on a null // if (requiredRoles.HasChild())
// string, so guard first) ... // {
// //
// 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() // // Referenced Scopes must exist ...
? [] // if (requiredScopes.HasChild())
: item.RequiredRoles.ParseListString<string>().ToList(); // {
// //
// 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(
var requiredScopes = item.RequiredScopes.IsNullOrEmpty() // XPolicyDefinitionDto item,
? [] // CancellationToken cancellationToken = default
: item.RequiredScopes.ParseListString<string>().ToList(); // )
// {
// //
// // Null / nameless guard ...
// if (item.IsNull() || item.Name.IsNullOrEmpty())
// {
// return null;
// }
// // //
// Referenced Roles must exist ... // // Parse the DTO's CSV-string RequiredRoles. ParseListString NREs on a
if (requiredRoles.HasChild()) // // null string, so guard first; the resolver itself is null-safe on an
{ // // empty explicitRoles set ...
// // var explicitRoles = item.RequiredRoles.IsNullOrEmpty()
var existingRoles = new HashSet<string>( // ? null
(await roles.GetAllAsync(cancellationToken: cancellationToken)) // : item.RequiredRoles.ParseListString<string>();
.Select(r => r.Name.ToNormalString()),
StringComparer.OrdinalIgnoreCase
);
if (requiredRoles.Any(r => !existingRoles.Contains(r.ToNormalString())))
{
XException.NotFound.Throw();
}
}
// // //
// Referenced Scopes must exist ... // // Resolve the effective role set
if (requiredScopes.HasChild()) // // (explicit RequiredRoles U roles by MinRoleWeight U parent chain) ...
{ // var effectiveRoles = await resolver.ResolveEffectiveRolesAsync(
// // explicitRoles: explicitRoles,
var existingScopes = new HashSet<string>( // minRoleWeight: item.MinRoleWeight,
(await scopes.GetAllAsync(cancellationToken: cancellationToken)) // 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, // // Project onto XEffectiveAuthorizationDto - the ONLY DTO that carries
CancellationToken cancellationToken = default // // 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) ...
// Null / nameless guard ... // var result = new XEffectiveAuthorizationDto
if (item.IsNull() || item.Name.IsNullOrEmpty()) // {
{ // PolicyName = item.Name,
return null; // 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 // return result;
// null string, so guard first; the resolver itself is null-safe on an // }
// empty explicitRoles set ... // #endregion
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
} }
} }
-94
View File
@@ -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);
}
}
}