Mon*_*kar 4 c# asp.net asp.net-mvc claims-based-identity asp.net-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));
Run Code Online (Sandbox Code Playgroud)
您可以使用此FindFirst(string type)方法ClaimsIdentity根据声明类型检索声明.在这种情况下Email或Email2
var claimType = "Email";
var claim = identity.FindFirst(claimType);
var email = claim == null ? string.Empty : claim.Value;
Run Code Online (Sandbox Code Playgroud)
我通常会将声明类型存储在常量中
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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后创建扩展方法,以便从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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4273 次 |
| 最近记录: |