Last active
July 24, 2021 12:12
-
-
Save jhoerr/6d3ba86e6f44a30457df to your computer and use it in GitHub Desktop.
Getting claims from an IPrincipal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using System.Security.Claims; | |
using System.Security.Principal; | |
namespace Common | |
{ | |
public static class PrincipalExtensions | |
{ | |
public static IEnumerable<string> Roles(this IPrincipal user) | |
{ | |
return ClaimsOfType(user, ClaimTypes.Role); | |
} | |
public static IEnumerable<string> Affiliations(this IPrincipal user) | |
{ | |
return ClaimsOfType(user, IUwareClaims.Affiliation); | |
} | |
public static IEnumerable<string> ClaimsOfType(this IPrincipal user, string claimType) | |
{ | |
if (!(user.Identity is ClaimsIdentity)) return new string[0]; | |
return ((ClaimsIdentity) user.Identity).Claims | |
.Where(c => c.Type.Equals(claimType)) | |
.Select(c => c.Value); | |
} | |
public static string ClaimOfType(this IPrincipal user, string claimType) | |
{ | |
return ClaimsOfType(user, claimType).FirstOrDefault(); | |
} | |
public static string Name(this IPrincipal user) | |
{ | |
return user.Identity.Name; | |
} | |
public static string DisplayName(this IPrincipal user) | |
{ | |
string surname = ClaimOfType(user, ClaimTypes.Surname); | |
string givenName = ClaimOfType(user, ClaimTypes.GivenName); | |
if (string.IsNullOrWhiteSpace(surname) && string.IsNullOrWhiteSpace(givenName)) return Name(user).TrimDomain(); | |
if (string.IsNullOrWhiteSpace(surname) || string.IsNullOrWhiteSpace(givenName)) return string.Format("{0}{1}", givenName ?? string.Empty, surname ?? string.Empty); | |
return string.Format("{0} {1}", givenName, surname); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment