42 lines
1.2 KiB
C#
42 lines
1.2 KiB
C#
using System.Security.Claims;
|
|
|
|
namespace Shogi.Api.Extensions;
|
|
|
|
public static class ClaimsExtensions
|
|
{
|
|
private static readonly string MsalUsernameClaim = "preferred_username";
|
|
|
|
public static string? GetGuestUserId(this ClaimsPrincipal self)
|
|
{
|
|
return self.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
|
|
}
|
|
|
|
public static string? DisplayName(this ClaimsPrincipal self)
|
|
{
|
|
return self.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
|
|
}
|
|
|
|
public static bool IsMicrosoft(this ClaimsPrincipal self)
|
|
{
|
|
return self.HasClaim(c => c.Type == MsalUsernameClaim);
|
|
}
|
|
|
|
public static string? GetMicrosoftUserId(this ClaimsPrincipal self)
|
|
{
|
|
return self.Claims.FirstOrDefault(c => c.Type == MsalUsernameClaim)?.Value;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reads the userId from claims after claims transformation has occurred.
|
|
/// Throws if a shogi userid is not found.
|
|
/// </summary>
|
|
/// <exception cref="InvalidOperationException"></exception>
|
|
public static string GetShogiUserId(this ClaimsPrincipal self)
|
|
{
|
|
var id = self.IsMicrosoft() ? self.GetMicrosoftUserId() : self.GetGuestUserId();
|
|
|
|
if (string.IsNullOrEmpty(id)) throw new InvalidOperationException("Shogi UserId not found in claims.");
|
|
|
|
return id;
|
|
}
|
|
} |