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

假装没事ソ 提交于 2019-12-07 07:30:54

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/39626368/asp-net-mvc-how-to-read-my-custom-claims-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!