Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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));
like image 360
Monojit Sarkar Avatar asked Sep 21 '16 20:09

Monojit Sarkar


1 Answers

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 then create extension methods to extract them from an IIdentity implementation provided it is derived from ClaimsIdentity.

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;
    }
}
like image 167
Nkosi Avatar answered Nov 13 '22 19:11

Nkosi