Compare commits
4
Commits
1cf90dcd9e
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49483d1d39 | ||
|
|
9d913146e1 | ||
|
|
384cffac36 | ||
|
|
869a0476a0 |
@@ -1,19 +1,22 @@
|
|||||||
using xIds.Interfaces;
|
using xIds.Interfaces;
|
||||||
using xCommons.Providers;
|
using xCommons.Providers;
|
||||||
|
using xCommons.Attributes;
|
||||||
using xIds.Controllers.Base;
|
using xIds.Controllers.Base;
|
||||||
using xCommons.Configurations;
|
using xCommons.Configurations;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
namespace xIds.Controllers
|
namespace xIds.Controllers
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Provide all available tools for manipulating users and accounts
|
/// Provide all available tools for manipulating users and accounts
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
[Authorize]
|
||||||
[ApiController]
|
[ApiController]
|
||||||
|
[RequireXPowered]
|
||||||
public partial class AccountController : XIBaseController
|
public partial class AccountController : XIBaseController
|
||||||
{
|
{
|
||||||
|
|
||||||
public AccountController(
|
public AccountController(
|
||||||
IXIdentityManager identityManager,
|
IXIdentityManager identityManager,
|
||||||
ILogger<AccountController> logger,
|
ILogger<AccountController> logger,
|
||||||
|
|||||||
@@ -1,17 +1,21 @@
|
|||||||
using xIds.Interfaces;
|
using xIds.Interfaces;
|
||||||
using xCommons.Providers;
|
using xCommons.Providers;
|
||||||
using xIds.Configurations;
|
using xIds.Configurations;
|
||||||
|
using xCommons.Attributes;
|
||||||
using xIds.Controllers.Base;
|
using xIds.Controllers.Base;
|
||||||
using xCommons.Configurations;
|
using xCommons.Configurations;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
namespace xIds.Controllers
|
namespace xIds.Controllers
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Provide all available tools for manipulating users and accounts
|
/// Provide all available tools for manipulating users and accounts
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
[Authorize]
|
||||||
[ApiController]
|
[ApiController]
|
||||||
|
[RequireXPowered]
|
||||||
public partial class ApplicationsController : XIBaseController
|
public partial class ApplicationsController : XIBaseController
|
||||||
{
|
{
|
||||||
private readonly IXApplicationProvider provider;
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,7 +19,8 @@ using xCommons.Authorization;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using xMessageService.Interfaces;
|
using xMessageService.Interfaces;
|
||||||
using xStorageService.Interfaces;
|
using xStorageService.Interfaces;
|
||||||
using xIdentityModels.Interfaces;
|
using xIdentityService.Providers;
|
||||||
|
using xIdentityService.Extensions;
|
||||||
using xIdentityService.Interfaces;
|
using xIdentityService.Interfaces;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -94,6 +95,13 @@ namespace xIds.DI
|
|||||||
source.AddScoped<IXRoleProvider, XRoleProvider>();
|
source.AddScoped<IXRoleProvider, XRoleProvider>();
|
||||||
source.AddScoped<IXScopeProvider, XScopeProvider>();
|
source.AddScoped<IXScopeProvider, XScopeProvider>();
|
||||||
source.AddScoped<IXPolicyProvider, XPolicyProvider>();
|
source.AddScoped<IXPolicyProvider, XPolicyProvider>();
|
||||||
|
|
||||||
|
//
|
||||||
|
source.AddXAuthorizationCache();
|
||||||
|
source.AddScoped<IXRoleHierarchyResolver, XRoleHierarchyResolver>();
|
||||||
|
|
||||||
|
//
|
||||||
|
source.AddXAuthorizationProvider();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -76,6 +76,24 @@ namespace xIds.DbContext
|
|||||||
e.HasIndex(k => k.KeyHash).IsUnique();
|
e.HasIndex(k => k.KeyHash).IsUnique();
|
||||||
e.HasIndex(k => k.ExpiresAt);
|
e.HasIndex(k => k.ExpiresAt);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
//
|
||||||
|
modelBuilder.Entity<XRoleDefinition>(e =>
|
||||||
|
{
|
||||||
|
e.HasIndex(p => p.Name).IsUnique();
|
||||||
|
});
|
||||||
|
|
||||||
|
//
|
||||||
|
modelBuilder.Entity<XScopeDefinition>(e =>
|
||||||
|
{
|
||||||
|
e.HasIndex(p => p.Name).IsUnique();
|
||||||
|
});
|
||||||
|
|
||||||
|
//
|
||||||
|
modelBuilder.Entity<XPolicyDefinition>(e =>
|
||||||
|
{
|
||||||
|
e.HasIndex(p => p.Name).IsUnique();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
using xIds.Providers;
|
using xIds.Providers;
|
||||||
using xIds.Interfaces;
|
using xIds.Interfaces;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using xExceptions.Constants;
|
||||||
|
using xIdentityService.Interfaces;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
namespace xIds.Extensions
|
namespace xIds.Extensions
|
||||||
@@ -25,5 +28,37 @@ namespace xIds.Extensions
|
|||||||
{
|
{
|
||||||
source.AddScoped<IXIdentityMessageProvider, XIdentityMessageProvider>();
|
source.AddScoped<IXIdentityMessageProvider, XIdentityMessageProvider>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Register Authorization Provider ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
public static void AddXAuthorizationProvider(
|
||||||
|
this IServiceCollection source
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate Requirements ...
|
||||||
|
var roles = source.GetRegisteredService<IXRoleProvider>();
|
||||||
|
var scopes = source.GetRegisteredService<IXScopeProvider>();
|
||||||
|
var policies = source.GetRegisteredService<IXPolicyProvider>();
|
||||||
|
var cache = source.GetRegisteredService<IXAuthorizationCache>();
|
||||||
|
var resolver = source.GetRegisteredService<IXRoleHierarchyResolver>();
|
||||||
|
|
||||||
|
//
|
||||||
|
var isInvalid =
|
||||||
|
roles.IsNull() ||
|
||||||
|
cache.IsNull() ||
|
||||||
|
scopes.IsNull() ||
|
||||||
|
policies.IsNull() ||
|
||||||
|
resolver.IsNull();
|
||||||
|
if (isInvalid)
|
||||||
|
{
|
||||||
|
XException.InvalidConfiguration.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
source.AddScoped<IXAuthorizationProvider, XAuthorizationProvider>();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -88,6 +88,10 @@ namespace xIds.Interfaces
|
|||||||
);
|
);
|
||||||
Task<IdentityResult> RemoveFromRoleAsync(XUser user, string roleName);
|
Task<IdentityResult> RemoveFromRoleAsync(XUser user, string roleName);
|
||||||
Task<IdentityResult> RemoveFromRolesAsync(XUser user, IEnumerable<string> roleNames);
|
Task<IdentityResult> RemoveFromRolesAsync(XUser user, IEnumerable<string> roleNames);
|
||||||
|
Task<IdentityResult> DeleteRoleAsync(
|
||||||
|
string roleName,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ namespace xIds.Providers
|
|||||||
AllowMultiple = false,
|
AllowMultiple = false,
|
||||||
Inherited = true
|
Inherited = true
|
||||||
)]
|
)]
|
||||||
public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter
|
public class XApiKeyAccessAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Optional allowed scopes. If empty, no scope enforcement.
|
/// Optional allowed scopes. If empty, no scope enforcement.
|
||||||
@@ -46,21 +46,7 @@ namespace xIds.Providers
|
|||||||
/// Authorization Filtering ...
|
/// Authorization Filtering ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="context"></param>
|
/// <param name="context"></param>
|
||||||
public void OnAuthorization(AuthorizationFilterContext context)
|
public async Task OnAuthorizationAsync(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
|
|
||||||
)
|
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
// Access HttpContext ...
|
// Access HttpContext ...
|
||||||
@@ -125,7 +111,7 @@ namespace xIds.Providers
|
|||||||
userInfo: null,
|
userInfo: null,
|
||||||
clientIP: clientIP,
|
clientIP: clientIP,
|
||||||
requiredScope: scopes,
|
requiredScope: scopes,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: default
|
||||||
);
|
);
|
||||||
if (validationResult.Errors.HasChild())
|
if (validationResult.Errors.HasChild())
|
||||||
{
|
{
|
||||||
@@ -155,5 +141,18 @@ namespace xIds.Providers
|
|||||||
context.Result = new UnauthorizedObjectResult(error);
|
context.Result = new UnauthorizedObjectResult(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <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
|
||||||
|
)
|
||||||
|
{
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
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 xIdentityModels.Models;
|
||||||
|
using xIdentityService.Models;
|
||||||
|
using xIdentityModels.Constants;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using IdentityServer4.Extensions;
|
||||||
|
using xIdentityService.Interfaces;
|
||||||
|
using xIdentityService.Extensions;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
|
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>
|
||||||
|
/// <param name="policyName"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task InvalidateAsync(string policyName = null)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (policyName.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
cache.Clear();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
cache.RemovePolicy(policyName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Build Authorization Policy ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="policyName"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<AuthorizationPolicy> BuildAuthorizationPolicyAsync(
|
||||||
|
string policyName,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var effective = await GetEffectiveAuthorizationAsync(policyName, cancellationToken);
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = effective.ToAuthorizationPolicy();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get Effective Authorization ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="target"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<XEffectiveAuthorizationDto> GetEffectiveAuthorizationAsync(
|
||||||
|
XUserClaimsInfoDto target,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Define Result ...
|
||||||
|
var result = new XEffectiveAuthorizationDto
|
||||||
|
{
|
||||||
|
EffectiveClaims = [],
|
||||||
|
RequireEnabledUser = !target.IsNull(),
|
||||||
|
RequireAuthenticatedUser = !target.IsNull(),
|
||||||
|
EffectiveRoles = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
|
||||||
|
EffectiveScopes = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
// Validate ...
|
||||||
|
if (target.IsNull())
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Effective roles = the user's actual roles (from RoleManager) ...
|
||||||
|
var userRoles = await GetUserRolesAsync(
|
||||||
|
cancellationToken: cancellationToken,
|
||||||
|
userId: target.GetUserSelectByParam(userSelectBy: XUserSelectBy.ID)
|
||||||
|
);
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get Effective Authorization ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="policyName"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<XEffectiveAuthorizationDto> GetEffectiveAuthorizationAsync(
|
||||||
|
string policyName,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (policyName.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var policy = await FindPolicyOrThrowAsync(policyName, cancellationToken);
|
||||||
|
var effective = await ToDtoWithEffectiveRolesAsync(policy, cancellationToken);
|
||||||
|
if (effective.IsNull())
|
||||||
|
{
|
||||||
|
XException.InvalidConfiguration.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return effective;
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
//
|
||||||
|
#region Private ...
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<string>> GetUserRolesAsync(
|
||||||
|
string userId,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (userId.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
//
|
||||||
|
var user = await manager.UserManager.FindByIdAsync(userId);
|
||||||
|
if (user.IsNull())
|
||||||
|
{
|
||||||
|
XException.NotFound.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = await manager.UserManager.GetRolesAsync(user);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
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<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,250 @@
|
|||||||
|
using xModels.Dtos;
|
||||||
|
using System.Threading;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using xIdentityModels.Dtos;
|
||||||
|
using xExceptions.Constants;
|
||||||
|
using xIdentityModels.Models;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using xIdentityService.Models;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace xIds.Providers
|
||||||
|
{
|
||||||
|
public partial class XAuthorizationProvider
|
||||||
|
{
|
||||||
|
//
|
||||||
|
#region Policy ...
|
||||||
|
public async Task<bool> RemovePolicyAsync(
|
||||||
|
string name,
|
||||||
|
XUserClaimsInfoDto userInfo,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var existing = await FindPolicyOrThrowAsync(name, cancellationToken);
|
||||||
|
if (existing.IsSystem)
|
||||||
|
{
|
||||||
|
XException.NotAllowed.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
await policies.RemoveAsync(
|
||||||
|
id: existing.Id,
|
||||||
|
userInfo: userInfo,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
await InvalidateAsync(existing.Name);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<XPolicyDefinitionDto> GetPolicyAsync(
|
||||||
|
string name,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = await FindPolicyOrThrowAsync(name, cancellationToken);
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<XPolicyDefinitionDto> AddPolicyAsync(
|
||||||
|
XPolicyDefinitionDto item,
|
||||||
|
XUserClaimsInfoDto userInfo,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// ⚠️ CRITICAL: مقصد همه Role/Scopeها وجود داشته باشند
|
||||||
|
await ValidateReferencesAsync(item, cancellationToken);
|
||||||
|
|
||||||
|
//
|
||||||
|
item.IsSystem = false;
|
||||||
|
var result = await policies.AddAsync(
|
||||||
|
item: item,
|
||||||
|
userInfo: userInfo,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
await InvalidateAsync();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<XPolicyDefinitionDto> UpdatePolicyAsync(
|
||||||
|
string name,
|
||||||
|
XPolicyDefinitionDto item,
|
||||||
|
XUserClaimsInfoDto userInfo,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (name.IsNullOrEmpty() || item.IsNull())
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var existing = await FindPolicyOrThrowAsync(name, cancellationToken);
|
||||||
|
if (existing.IsSystem)
|
||||||
|
{
|
||||||
|
XException.NotAllowed.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Reference validation BEFORE update — same as Add
|
||||||
|
await ValidateReferencesAsync(item, cancellationToken);
|
||||||
|
|
||||||
|
//
|
||||||
|
var updated = await policies.UpdateAsync(
|
||||||
|
id: existing.Id,
|
||||||
|
item: item,
|
||||||
|
userInfo: userInfo,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
await InvalidateAsync(existing.Name);
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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<IEnumerable<XPolicyDefinitionDto>> GetPoliciesAsync(
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = await policies
|
||||||
|
.GetAllAsync(cancellationToken: cancellationToken);
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
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 xIds.Providers
|
||||||
|
{
|
||||||
|
public partial class XAuthorizationProvider
|
||||||
|
{
|
||||||
|
//
|
||||||
|
#region Role ...
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<int> CountUsersInRoleAsync(
|
||||||
|
string name,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Fail fast if the role itself does not exist ...
|
||||||
|
await FindRoleOrThrowAsync(name, cancellationToken);
|
||||||
|
|
||||||
|
//
|
||||||
|
var usersInRole = await manager
|
||||||
|
.UserManager.GetUsersInRoleAsync(name);
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = usersInRole.Count();
|
||||||
|
|
||||||
|
//
|
||||||
|
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() ||
|
||||||
|
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<IEnumerable<XRoleDefinitionDto>> GetRolesAsync(
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = await roles
|
||||||
|
.GetAllAsync(cancellationToken: cancellationToken);
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<XQueryResult<XRoleDefinitionDto>> QueryRolesAsync(
|
||||||
|
XQuery query,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate ...
|
||||||
|
if (query.IsNull())
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = await roles.QueryAsync(
|
||||||
|
query: query,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
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 xIds.Providers
|
||||||
|
{
|
||||||
|
public partial class XAuthorizationProvider
|
||||||
|
{
|
||||||
|
//
|
||||||
|
#region Scope ...
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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<IEnumerable<XScopeDefinitionDto>> GetScopesAsync(
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
return await scopes
|
||||||
|
.GetAllAsync(cancellationToken: cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
#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.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.AspNetCore.Identity;
|
using Microsoft.AspNetCore.Identity;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
@@ -211,6 +212,55 @@ namespace xIds.Providers
|
|||||||
return result;
|
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>
|
/// <summary>
|
||||||
/// Check a User is Adminr not
|
/// Check a User is Adminr not
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
+3
-3
@@ -80,12 +80,12 @@ namespace xIds
|
|||||||
|
|
||||||
//
|
//
|
||||||
// Register Security Provider ...
|
// Register Security Provider ...
|
||||||
services.AddSingleton<IXSecurityProvider, XSecurityProvider>();
|
services.AddSingleton<IXSecurityProvider, XSecurityProvider>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Configure(
|
public void Configure(
|
||||||
IApplicationBuilder app,
|
IApplicationBuilder app,
|
||||||
IWebHostEnvironment env,
|
IWebHostEnvironment env,
|
||||||
ILogger<Startup> logger
|
ILogger<Startup> logger
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in New Issue
Block a user