Created
March 26, 2017 13:13
-
-
Save DejanMilicic/f7b4e429d6c05898595d3b8795ceebe9 to your computer and use it in GitHub Desktop.
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.Linq; | |
using System.Security.Claims; | |
using System.Security.Principal; | |
namespace Infrastructure.Claims | |
{ | |
public static class ClaimExtensions | |
{ | |
public static void AddUpdateClaim(this IPrincipal currentPrincipal, string key, string value) | |
{ | |
var identity = currentPrincipal.Identity as ClaimsIdentity; | |
if (identity == null) | |
return; | |
// check for existing claim and remove it | |
var existingClaim = identity.FindFirst(key); | |
if (existingClaim != null) | |
identity.RemoveClaim(existingClaim); | |
// add new claim | |
identity.AddClaim(new Claim(key, value)); | |
} | |
public static string GetClaimValue(this IPrincipal currentPrincipal, string key) | |
{ | |
var identity = currentPrincipal.Identity as ClaimsIdentity; | |
if (identity == null) | |
return null; | |
var claim = identity.Claims.FirstOrDefault(c => c.Type == key); | |
return claim?.Value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment