Monojit Sarkar Monojit Sarkar - 2 months ago 30
C# Question

ASP.Net MVC: How to read my custom claims value

see the below code. i got to know that this way we can add our custom data to claims but now question is how to read back those value. say i want to read back value for claims Email and Email2 please tell me what code i need to write to read back value for claims Email and Email2 thanks

UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext()));
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie
var user = userManager.Find(userName, password);
identity.AddClaim(new Claim("Email", user.Email));
identity.AddClaim(new Claim("Email2", user.Email));

Answer

You could use the FindFirst(string type) method on ClaimsIdentity to retrieve the claim based on the claim type. In this case Email or Email2

var claimType = "Email";
var claim = identity.FindFirst(claimType);
var email = claim == null ? string.Empty : claim.Value;

I would normally store the claim types in constants

public static partial class Constants {
    public class Security {
        public static class ClaimTypes {
            public const string Email = "http://schemas.mycompany.com/identity/claims/email";
            public const string Email2 = "http://schemas.mycompany.com/identity/claims/email2";
        }
    }
}

and the create extension methods to extract them from identity.

public static class GenericIdentityExtensions {
    /// <summary>
    /// Return the Email claim
    /// </summary>
    public static string GetEmail(this IIdentity identity) {
        if (identity != null && identity.IsAuthenticated) {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            if (claimsIdentity != null)
                return claimsIdentity.FindFirstOrEmpty(Constants.Security.ClaimTypes.Email);
        }
        return string.Empty;
    }
    /// <summary>
    /// Return the Email2 claim
    /// </summary>
    public static string GetEmail2(this IIdentity identity) {
        if (identity != null && identity.IsAuthenticated) {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            if (claimsIdentity != null)
                return claimsIdentity.FindFirstOrEmpty(Constants.Security.ClaimTypes.Email2);
        }
        return string.Empty;
    }
    /// <summary>
    /// Retrieves the first claim that is matched by the specified type if it exists, String.Empty otherwise.
    /// </summary>
    internal static string FindFirstOrEmpty(this ClaimsIdentity identity, string claimType) {
        var claim = identity.FindFirst(claimType);
        return claim == null ? string.Empty : claim.Value;
    }
}