92 lines
2.8 KiB
C#
92 lines
2.8 KiB
C#
using maintenance.Authentication.Configuration;
|
|
using maintenance.Data;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using System.Security.Claims;
|
|
|
|
namespace maintenance.Authentication.Core;
|
|
|
|
public sealed class AdminRoleClaimsTransformation : IClaimsTransformation
|
|
{
|
|
private static readonly string[] GroupClaimTypes =
|
|
{
|
|
"groups",
|
|
"group",
|
|
"role",
|
|
"roles",
|
|
ClaimTypes.GroupSid,
|
|
ClaimTypes.Role,
|
|
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
|
|
"http://schemas.xmlsoap.org/claims/Group"
|
|
};
|
|
|
|
private readonly IConfiguration _configuration;
|
|
private readonly AppDbContext _dbContext;
|
|
|
|
public AdminRoleClaimsTransformation(IConfiguration configuration, AppDbContext dbContext)
|
|
{
|
|
_configuration = configuration;
|
|
_dbContext = dbContext;
|
|
}
|
|
|
|
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
|
|
{
|
|
if (principal.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated)
|
|
{
|
|
return principal;
|
|
}
|
|
|
|
if (identity.Claims.Any(c => c.Type == ClaimTypes.Role && c.Value == AuthRoles.Admin))
|
|
{
|
|
return principal;
|
|
}
|
|
|
|
var configuredGroups = (_configuration[AuthEnvironment.AdminGroups] ?? string.Empty)
|
|
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
|
|
|
var groupSource = _configuration[AuthEnvironment.AdminGroupSource] ?? AdminGroupSources.Max;
|
|
List<string> dbGroups;
|
|
|
|
if (groupSource.Equals(AdminGroupSources.Ad, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
dbGroups = await _dbContext.AuthorizationGroups
|
|
.AsNoTracking()
|
|
.Where(g => g.Active && g.Role == "admin")
|
|
.Select(g => g.GroupClaimValue)
|
|
.ToListAsync();
|
|
}
|
|
else
|
|
{
|
|
dbGroups = await _dbContext.AdminGroups
|
|
.AsNoTracking()
|
|
.Select(g => g.GroupClaimValue)
|
|
.ToListAsync();
|
|
}
|
|
|
|
var effectiveGroups = configuredGroups
|
|
.Concat(dbGroups)
|
|
.Distinct(StringComparer.OrdinalIgnoreCase)
|
|
.ToArray();
|
|
|
|
if (effectiveGroups.Length == 0)
|
|
{
|
|
return principal;
|
|
}
|
|
|
|
var principalGroups = identity.Claims
|
|
.Where(c => GroupClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
|
|
.Select(c => c.Value);
|
|
|
|
var isAdmin = principalGroups.Any(group =>
|
|
effectiveGroups.Contains(group, StringComparer.OrdinalIgnoreCase));
|
|
|
|
if (isAdmin)
|
|
{
|
|
identity.AddClaim(new Claim(ClaimTypes.Role, AuthRoles.Admin));
|
|
}
|
|
|
|
return principal;
|
|
}
|
|
}
|
|
|