62 lines
1.9 KiB
C#
62 lines
1.9 KiB
C#
using MaxInventory.Authentication.Abstractions;
|
|
using System.Security.Claims;
|
|
|
|
namespace MaxInventory.Authentication.Core
|
|
{
|
|
public sealed class IdentityContextFactory : IIdentityContextFactory
|
|
{
|
|
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 static readonly string[] RoleClaimTypes =
|
|
{
|
|
"role",
|
|
"roles",
|
|
ClaimTypes.Role,
|
|
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
|
|
};
|
|
|
|
public IdentityContext Create(ClaimsPrincipal principal)
|
|
{
|
|
var groups = principal.Claims
|
|
.Where(c => GroupClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
|
|
.Select(c => c.Value)
|
|
.Distinct(StringComparer.OrdinalIgnoreCase)
|
|
.ToArray();
|
|
|
|
var roles = principal.Claims
|
|
.Where(c => RoleClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
|
|
.Select(c => c.Value)
|
|
.Distinct(StringComparer.OrdinalIgnoreCase)
|
|
.ToArray();
|
|
|
|
var userId = principal.FindFirstValue(ClaimTypes.NameIdentifier)
|
|
?? principal.FindFirstValue("sub")
|
|
?? principal.Identity?.Name
|
|
?? "unknown";
|
|
|
|
var displayName = principal.FindFirstValue(ClaimTypes.Name)
|
|
?? principal.Identity?.Name
|
|
?? userId;
|
|
|
|
return new IdentityContext
|
|
{
|
|
UserId = userId,
|
|
DisplayName = displayName,
|
|
Groups = groups,
|
|
Roles = roles
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|