ASP.Net MVC:如何读取我的自定义声明值

时间:2016-09-21 20:51:01

标签: c# asp.net-mvc asp.net-identity claims-based-identity

请参阅以下代码。我知道这样我们可以将自定义数据添加到声明中,但现在的问题是如何读回这些值。说我想回读索赔的价值电子邮件和电子邮件2 请告诉我需要写什么代码来回读索赔的值电子邮件和电子邮件2

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));

1 个答案:

答案 0 :(得分:6)

您可以使用FindFirst(string type)上的ClaimsIdentity方法根据声明类型检索声明。在这种情况下EmailEmail2

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

我通常会将声明类型存储在常量

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";
        }
    }
}

然后创建扩展方法,以便从IIdentity实现中提取它们,前提是它来自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;
    }
}