-
Notifications
You must be signed in to change notification settings - Fork 533
/
UserInfo.cs
31 lines (25 loc) · 1.17 KB
/
UserInfo.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System.Security.Claims;
namespace BlazorWebAppOidc.Client;
// Add properties to this class and update the server and client AuthenticationStateProviders
// to expose more information about the authenticated user to the client.
public sealed class UserInfo
{
public required string UserId { get; init; }
public required string Name { get; init; }
public const string UserIdClaimType = "sub";
public const string NameClaimType = "name";
public static UserInfo FromClaimsPrincipal(ClaimsPrincipal principal) =>
new()
{
UserId = GetRequiredClaim(principal, UserIdClaimType),
Name = GetRequiredClaim(principal, NameClaimType),
};
public ClaimsPrincipal ToClaimsPrincipal() =>
new(new ClaimsIdentity(
[new(UserIdClaimType, UserId), new(NameClaimType, Name)],
authenticationType: nameof(UserInfo),
nameType: NameClaimType,
roleType: null));
private static string GetRequiredClaim(ClaimsPrincipal principal, string claimType) =>
principal.FindFirst(claimType)?.Value ?? throw new InvalidOperationException($"Could not find required '{claimType}' claim.");
}