389 lines
12 KiB
C#
389 lines
12 KiB
C#
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
|
|
}
|
|
} |