Skip to content

Instantly share code, notes, and snippets.

@DejanMilicic
Created March 26, 2017 13:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DejanMilicic/f7b4e429d6c05898595d3b8795ceebe9 to your computer and use it in GitHub Desktop.
Save DejanMilicic/f7b4e429d6c05898595d3b8795ceebe9 to your computer and use it in GitHub Desktop.
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