Compare commits
1
Commits
869a0476a0
...
384cffac36
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
384cffac36 |
@@ -1,19 +1,22 @@
|
||||
using xIds.Interfaces;
|
||||
using xCommons.Providers;
|
||||
using xCommons.Attributes;
|
||||
using xIds.Controllers.Base;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace xIds.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Provide all available tools for manipulating users and accounts
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
[RequireXPowered]
|
||||
public partial class AccountController : XIBaseController
|
||||
{
|
||||
|
||||
public AccountController(
|
||||
IXIdentityManager identityManager,
|
||||
ILogger<AccountController> logger,
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
using xIds.Interfaces;
|
||||
using xCommons.Providers;
|
||||
using xIds.Configurations;
|
||||
using xCommons.Attributes;
|
||||
using xIds.Controllers.Base;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace xIds.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Provide all available tools for manipulating users and accounts
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
[RequireXPowered]
|
||||
public partial class ApplicationsController : XIBaseController
|
||||
{
|
||||
private readonly IXApplicationProvider provider;
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace xIds.Controllers
|
||||
{
|
||||
public partial class AuthorizationController
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using xIdentityHelper;
|
||||
using System.Threading;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Dtos;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace xIds.Controllers
|
||||
{
|
||||
public partial class AuthorizationController
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieve Specified Role By Id ...
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("Roles/{id}")]
|
||||
[Authorize(Policy = XPolicies.EnabledAdmin)]
|
||||
public virtual async Task<ActionResult<XRoleDefinitionDto>> Get(
|
||||
[FromRoute] int id,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (!id.IsValidIntId())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
|
||||
//
|
||||
var result = await roleProvider.GetAsync(
|
||||
id: id,
|
||||
ignoreSoftDeleteds: true,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
return Ok(result.ToDynamicObject());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace xIds.Controllers
|
||||
{
|
||||
public partial class AuthorizationController
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using xIds.Interfaces;
|
||||
using xCommons.Providers;
|
||||
using xCommons.Attributes;
|
||||
using xIds.Controllers.Base;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using xIdentityService.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace xIds.Controllers
|
||||
{
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
[RequireXPowered]
|
||||
public partial class AuthorizationController : XIBaseController
|
||||
{
|
||||
private readonly IXRoleProvider roleProvider;
|
||||
private readonly IXScopeProvider scopeProvider;
|
||||
private readonly IXPolicyProvider policyProvider;
|
||||
|
||||
public AuthorizationController(
|
||||
IXRoleProvider roleProvider,
|
||||
IXScopeProvider scopeProvider,
|
||||
IXPolicyProvider policyProvider,
|
||||
IXIdentityManager identityManager,
|
||||
XAppConfiguration appConfiguration,
|
||||
XValidationProvider validationProvider,
|
||||
ILogger<AuthorizationController> logger
|
||||
) : base(logger, appConfiguration, identityManager, validationProvider)
|
||||
{
|
||||
//
|
||||
this.roleProvider = roleProvider;
|
||||
this.scopeProvider = scopeProvider;
|
||||
this.policyProvider = policyProvider;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,12 +14,12 @@ using xMessageService.DI;
|
||||
using xStorageService.DI;
|
||||
using xCommons.Extensions;
|
||||
using xIds.Configurations;
|
||||
using xIdentityService.DI;
|
||||
using xExceptions.Constants;
|
||||
using xCommons.Authorization;
|
||||
using System.Collections.Generic;
|
||||
using xMessageService.Interfaces;
|
||||
using xStorageService.Interfaces;
|
||||
using xIdentityModels.Interfaces;
|
||||
using xIdentityService.Interfaces;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -94,6 +94,9 @@ namespace xIds.DI
|
||||
source.AddScoped<IXRoleProvider, XRoleProvider>();
|
||||
source.AddScoped<IXScopeProvider, XScopeProvider>();
|
||||
source.AddScoped<IXPolicyProvider, XPolicyProvider>();
|
||||
|
||||
//
|
||||
source.AddXAuthorizationProvider();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -88,6 +88,10 @@ namespace xIds.Interfaces
|
||||
);
|
||||
Task<IdentityResult> RemoveFromRoleAsync(XUser user, string roleName);
|
||||
Task<IdentityResult> RemoveFromRolesAsync(XUser user, IEnumerable<string> roleNames);
|
||||
Task<IdentityResult> DeleteRoleAsync(
|
||||
string roleName,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using xIds.Interfaces;
|
||||
using System.Threading;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Dtos;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityService.Models;
|
||||
using System.Collections.Generic;
|
||||
using IdentityServer4.Extensions;
|
||||
using xIdentityService.Interfaces;
|
||||
using xIdentityService.Extensions;
|
||||
|
||||
namespace xIds.Providers
|
||||
{
|
||||
public partial class XAuthorizationProvider : IXAuthorizationProvider
|
||||
{
|
||||
//
|
||||
private readonly IXRoleProvider roles;
|
||||
private readonly IXScopeProvider scopes;
|
||||
private readonly IXIdentityManager manager;
|
||||
private readonly IXPolicyProvider policies;
|
||||
private readonly IXAuthorizationCache cache;
|
||||
private readonly IXRoleHierarchyResolver resolver;
|
||||
|
||||
public XAuthorizationProvider(
|
||||
IXRoleProvider roles,
|
||||
IXScopeProvider scopes,
|
||||
IXIdentityManager manager,
|
||||
IXPolicyProvider policies,
|
||||
IXAuthorizationCache cache,
|
||||
IXRoleHierarchyResolver resolver
|
||||
)
|
||||
{
|
||||
//
|
||||
this.roles = roles;
|
||||
this.cache = cache;
|
||||
this.scopes = scopes;
|
||||
this.manager = manager;
|
||||
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,181 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Dtos;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityModels.Models;
|
||||
|
||||
namespace xIds.Providers
|
||||
{
|
||||
public partial class XAuthorizationProvider
|
||||
{
|
||||
//
|
||||
#region Role ...
|
||||
public async Task<XRoleDefinitionDto> AddRoleAsync(
|
||||
XRoleDefinitionDto item,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (item.IsNull() ||
|
||||
item.Name.IsNullOrEmpty() ||
|
||||
userInfo.IsNullOrDefault()
|
||||
)
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Duplicate check via repository (NOT AsQueryable) ...
|
||||
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 locally first
|
||||
item.IsSystem = false;
|
||||
var result = await roles.AddAsync(
|
||||
item: item,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
// Sync to IdentityServer — MUST check result
|
||||
var identityResult = await manager.CreateRoleAsync(result.Name);
|
||||
if (!identityResult.Succeeded)
|
||||
{
|
||||
//
|
||||
// Rollback local insert to avoid permanent drift
|
||||
await roles.RemoveAsync(
|
||||
id: result.Id,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
XException.ActionFailed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
await InvalidateAsync();
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<XRoleDefinitionDto> UpdateRoleAsync(
|
||||
string name,
|
||||
XRoleDefinitionDto item,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
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(
|
||||
item: item,
|
||||
id: existing.Id,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
// Sync to IdentityServer — rename requires delete+create in IdentityServer
|
||||
if (!string.Equals(
|
||||
existing.Name,
|
||||
updated.Name,
|
||||
StringComparison.OrdinalIgnoreCase)
|
||||
)
|
||||
{
|
||||
//
|
||||
var usersInRole = await manager.UserManager
|
||||
.GetUsersInRoleAsync(existing.Name.ToNormalString());
|
||||
|
||||
//
|
||||
await manager.DeleteRoleAsync(
|
||||
existing.Name,
|
||||
cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
var identityResult = await manager.CreateRoleAsync(updated.Name);
|
||||
if (!identityResult.Succeeded)
|
||||
{
|
||||
XException.ActionFailed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
foreach(var user in usersInRole)
|
||||
{
|
||||
//
|
||||
await manager.AddUserToRoleAsync(
|
||||
user: user,
|
||||
roleName: updated.Name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
await InvalidateAsync();
|
||||
return updated;
|
||||
}
|
||||
|
||||
public async Task<bool> RemoveRoleAsync(
|
||||
string name,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var existing = await FindRoleOrThrowAsync(name, cancellationToken);
|
||||
if (existing.IsSystem)
|
||||
{
|
||||
XException.NotAllowed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// ⚠️ CRITICAL: capture affected users BEFORE delete.
|
||||
// After DeleteRoleAsync, AspNetUserRoles rows are gone.
|
||||
var affectedUsers = await manager.UserManager.GetUsersInRoleAsync(existing.Name);
|
||||
var affectedUserIds = affectedUsers.Select(u => u.Id).ToList();
|
||||
|
||||
//
|
||||
// Delete from local DB
|
||||
await roles.RemoveAsync(
|
||||
id: existing.Id,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
// Delete from IdentityServer — this cascades AspNetUserRoles
|
||||
await manager.DeleteRoleAsync(existing.Name, cancellationToken);
|
||||
|
||||
//
|
||||
await InvalidateAsync();
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
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 xIds.Providers
|
||||
{
|
||||
public partial class XAuthorizationProvider
|
||||
{
|
||||
//
|
||||
#region Scope ...
|
||||
public async Task<IEnumerable<XScopeDefinitionDto>> GetScopesAsync(
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
return await scopes
|
||||
.GetAllAsync(cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<XScopeDefinitionDto> GetScopeAsync(
|
||||
string name,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
return await FindScopeOrThrowAsync(name, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<XScopeDefinitionDto> AddScopeAsync(
|
||||
XScopeDefinitionDto item,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
if (item.IsNull() || item.Name.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var normalized = item.Name.ToNormalString();
|
||||
var exists = await scopes.FindOneAsync(
|
||||
predicate: s => s.Name.ToLower() == normalized,
|
||||
cancellationToken: cancellationToken);
|
||||
if (!exists.IsNull())
|
||||
{
|
||||
XException.Duplicate.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
item.IsSystem = false;
|
||||
var result = await scopes.AddAsync(
|
||||
item: item,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
await InvalidateAsync();
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<XScopeDefinitionDto> UpdateScopeAsync(
|
||||
string name,
|
||||
XScopeDefinitionDto item,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
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(
|
||||
item: item,
|
||||
id: existing.Id,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
await InvalidateAsync();
|
||||
return updated;
|
||||
}
|
||||
|
||||
public async Task<bool> RemoveScopeAsync(
|
||||
string name,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var existing = await FindScopeOrThrowAsync(name, cancellationToken);
|
||||
if (existing.IsSystem) {
|
||||
XException.NotAllowed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var affectedPolicies = (await policies.GetAllAsync(cancellationToken: cancellationToken))
|
||||
.Where(p => !p.RequiredScopes.IsNullOrEmpty()
|
||||
&& p.RequiredScopes.ParseListString<string>()
|
||||
.Any(s => string.Equals(s, existing.Name,
|
||||
StringComparison.OrdinalIgnoreCase)))
|
||||
.ToList();
|
||||
|
||||
//
|
||||
await scopes.RemoveAsync(
|
||||
id: existing.Id,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
await InvalidateAsync();
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
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 xIds.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);
|
||||
}
|
||||
|
||||
public Task<AuthorizationPolicy> GetFallbackPolicyAsync()
|
||||
{
|
||||
return Task.FromResult<AuthorizationPolicy>(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using xCommons.Extensions;
|
||||
@@ -211,6 +212,55 @@ namespace xIds.Providers
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete a Role from Identity store (AspNetRoles) and cascade remove
|
||||
/// all user assignments (AspNetUserRoles).
|
||||
/// </summary>
|
||||
/// <param name="roleName">role name</param>
|
||||
/// <param name="cancellationToken">cancellation token (best-effort; Identity APIs are not cancellable)</param>
|
||||
/// <returns>an instance of <see>IdentityResult</see></returns>
|
||||
public async Task<IdentityResult> DeleteRoleAsync(
|
||||
string roleName,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate Args ...
|
||||
if (roleName.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Honor cancellation at the entry point. RoleManager.DeleteAsync does not
|
||||
// accept a CancellationToken, so this is a best-effort check before the call.
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
//
|
||||
// Retrieve the role — throws XException.NotFound if it does not exist
|
||||
var role = await GetRoleAsync(roleName);
|
||||
|
||||
//
|
||||
var usersInRole = await UserManager.GetUsersInRoleAsync(roleName);
|
||||
foreach(var user in usersInRole)
|
||||
{
|
||||
//
|
||||
await UserManager.RemoveFromRoleAsync(
|
||||
user: user,
|
||||
role: roleName
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
// Persist deletion. EF cascades to AspNetUserRoles automatically
|
||||
// under the default Identity configuration (IdentityUserRole<string>).
|
||||
var result = await RoleManager.DeleteAsync(role);
|
||||
|
||||
//
|
||||
// Return Result ...
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check a User is Adminr not
|
||||
/// </summary>
|
||||
|
||||
+20
-4
@@ -80,12 +80,12 @@ namespace xIds
|
||||
|
||||
//
|
||||
// Register Security Provider ...
|
||||
services.AddSingleton<IXSecurityProvider, XSecurityProvider>();
|
||||
services.AddSingleton<IXSecurityProvider, XSecurityProvider>();
|
||||
}
|
||||
|
||||
public void Configure(
|
||||
IApplicationBuilder app,
|
||||
IWebHostEnvironment env,
|
||||
IApplicationBuilder app,
|
||||
IWebHostEnvironment env,
|
||||
ILogger<Startup> logger
|
||||
)
|
||||
{
|
||||
@@ -133,7 +133,23 @@ namespace xIds
|
||||
//
|
||||
app.UseEndpoints(endpoints =>
|
||||
{
|
||||
endpoints.MapDefaultControllerRoute();
|
||||
//
|
||||
// endpoints.MapDefaultControllerRoute();
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
endpoints.MapDefaultControllerRoute();
|
||||
}
|
||||
catch (ReflectionTypeLoadException ex)
|
||||
{
|
||||
foreach (var loaderException in ex.LoaderExceptions)
|
||||
{
|
||||
// Log or inspect the specific error, e.g., "Could not load file or assembly..."
|
||||
Console.WriteLine(loaderException?.Message);
|
||||
}
|
||||
throw; // Re-throw to preserve the original behavior
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user