Skip to content

Commit 75e64e6

Browse files
committed
Add GetUserName method to ClaimsPrincipalExtensions
Introduce a new extension method `GetUserName` in the `ClaimsPrincipalExtensions` class within the `EasyExtensions` namespace. This method retrieves the user's name or unique identifier by checking claims in the following order of precedence: `ClaimTypes.Name`, "sub", and `ClaimTypes.NameIdentifier`. Throw a `KeyNotFoundException` if none of these claims are found and a `NullReferenceException` if the `user` parameter is null. Include detailed XML documentation for the method, describing its purpose, behavior, parameters, return value, and exceptions.
1 parent dee9db0 commit 75e64e6

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Sources/EasyExtensions/Extensions/ClaimsPrincipalExtensions.cs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,44 @@ namespace EasyExtensions
99
/// </summary>
1010
public static class ClaimsPrincipalExtensions
1111
{
12+
/// <summary>
13+
/// Retrieves the user name or unique identifier from the specified claims principal.
14+
/// </summary>
15+
/// <remarks>This method attempts to retrieve the user's name by first checking for a name claim
16+
/// (<see cref="System.Security.Claims.ClaimTypes.Name"/>), then a subject claim ('sub'), and finally a name
17+
/// identifier claim (<see cref="System.Security.Claims.ClaimTypes.NameIdentifier"/>). If none of these claims
18+
/// are found, an exception is thrown.</remarks>
19+
/// <param name="user">The claims principal from which to extract the user name. Cannot be null.</param>
20+
/// <returns>A string containing the user's name, subject identifier ('sub'), or name identifier claim value, in that
21+
/// order of precedence.</returns>
22+
/// <exception cref="NullReferenceException">Thrown if the <paramref name="user"/> parameter is null.</exception>
23+
/// <exception cref="KeyNotFoundException">Thrown if neither a name, subject ('sub'), nor name identifier claim is present in the claims principal.</exception>
24+
public static string GetUserName(this ClaimsPrincipal? user)
25+
{
26+
if (user == null)
27+
{
28+
throw new NullReferenceException(nameof(user));
29+
}
30+
Claim? name = user.FindFirst(ClaimTypes.Name);
31+
if (name != null)
32+
{
33+
return name.Value;
34+
}
35+
Claim? sub = user.FindFirst("sub");
36+
if (sub != null)
37+
{
38+
return sub.Value;
39+
}
40+
41+
Claim? nameIdentifier = user.FindFirst(ClaimTypes.NameIdentifier);
42+
if (nameIdentifier != null)
43+
{
44+
return nameIdentifier.Value;
45+
}
46+
47+
throw new KeyNotFoundException("'sub' or " + ClaimTypes.NameIdentifier);
48+
}
49+
1250
/// <summary>
1351
/// Attempts to extract the user's unique identifier from the specified claims principal.
1452
/// </summary>

0 commit comments

Comments
 (0)