Skip to content

Instantly share code, notes, and snippets.

@jburditt
Created May 24, 2016 23:13
Show Gist options
  • Save jburditt/7961f415b1b39df36182465b85f6950a to your computer and use it in GitHub Desktop.
Save jburditt/7961f415b1b39df36182465b85f6950a to your computer and use it in GitHub Desktop.
using System.Linq;
using System.Security.Claims;
using Newtonsoft.Json;
namespace Account
{
public static class ClaimsExtensions
{
public static string Get(this ClaimsIdentity identity, string type)
{
return identity.Claims.FirstOrDefault(p => p.Type == type)?.Value;
}
public static T Get<T>(this ClaimsIdentity identity, string type) where T : new()
{
var json = identity.Claims.FirstOrDefault(p => p.Type == type)?.Value;
return json == null ? new T() : JsonConvert.DeserializeObject<T>(json);
}
public static void Set(this ClaimsIdentity identity, string type, string value)
{
identity.AddClaim(new Claim(type, value));
}
public static void Set<T>(this ClaimsIdentity identity, string type, T obj)
{
var json = JsonConvert.SerializeObject(obj);
identity.AddClaim(new Claim(type, json));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment