ASP.Net MVC:如何读取我的自定义声明值 [英] ASP.Net MVC: How to read my custom claims value
问题描述
请参见以下代码.我知道,通过这种方式我们可以将自定义数据添加到索赔中,但是现在的问题是如何读回这些值.假设我想回读声明 Email和Email2 的价值,请告诉我我需要写什么代码来回读声明 Email和Email2 的价值.
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));
推荐答案
您可以在ClaimsIdentity
上使用FindFirst(string type)
方法来根据声明类型检索声明.在这种情况下,Email
或Email2
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";
}
}
}
,然后创建扩展方法以从IIdentity
实现中提取它们,只要它是从ClaimsIdentity
派生的.
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;
}
}
这篇关于ASP.Net MVC:如何读取我的自定义声明值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!