Init
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
using maintenance.Authentication.Configuration;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace maintenance.Authentication.Core;
|
||||
|
||||
public sealed class AdminRoleClaimsTransformation : IClaimsTransformation
|
||||
{
|
||||
private static readonly string[] GroupClaimTypes =
|
||||
{
|
||||
"groups",
|
||||
"group",
|
||||
ClaimTypes.GroupSid,
|
||||
"http://schemas.xmlsoap.org/claims/Group"
|
||||
};
|
||||
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
public AdminRoleClaimsTransformation(IConfiguration configuration)
|
||||
{
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
|
||||
{
|
||||
if (principal.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated)
|
||||
{
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
|
||||
if (identity.Claims.Any(c => c.Type == ClaimTypes.Role && c.Value == AuthRoles.Admin))
|
||||
{
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
|
||||
var configuredGroups = (_configuration[AuthEnvironment.AdminGroups] ?? string.Empty)
|
||||
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
|
||||
if (configuredGroups.Length == 0)
|
||||
{
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
|
||||
var principalGroups = identity.Claims
|
||||
.Where(c => GroupClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
|
||||
.Select(c => c.Value);
|
||||
|
||||
var isAdmin = principalGroups.Any(group =>
|
||||
configuredGroups.Contains(group, StringComparer.OrdinalIgnoreCase));
|
||||
|
||||
if (isAdmin)
|
||||
{
|
||||
identity.AddClaim(new Claim(ClaimTypes.Role, AuthRoles.Admin));
|
||||
}
|
||||
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user