请参见下面的代码。我知道,通过这种方式我们可以将自定义数据添加到 claim 中,但是现在的问题是如何读回这些值。假设我想回读索偿电子邮件和Email2的值,请告诉我要回读索偿电子邮件和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));
最佳答案
您可以对FindFirst(string type)
使用ClaimsIdentity
方法来根据声明类型检索声明。在这种情况下,Email
或Email2
var claimType = "Email";
var claim = identity.FindFirst(claimType);
var email = claim == null ? string.Empty : claim.Value;
我通常将 claim 类型存储在常量中
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;
}
}
关于c# - ASP.Net MVC : How to read my custom claims value,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39626368/