所以在登录期间我创建了声明。但是我似乎失去了我的自定义声明(UserData)。以下是我创建声明的代码:
// create required claims
claims.Add(new Claim(ClaimTypes.NameIdentifier, UserContext.UserId.ToString()));
claims.Add(new Claim(ClaimTypes.Name, UserContext.Email));
// custom – my serialized UserContext object
claims.Add(new Claim(ClaimTypes.UserData, UserContext.Serialize(UserContext)));
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent, AllowRefresh = true }, identity);
检查ClaimsIdentity(身份)我看到:
{http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: 12
{http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: test@test.com}
{http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata: Something}
因此,在调试期间,我会立即获得当前的校长:
var identity1 = (ClaimsPrincipal)System.Threading.Thread.CurrentPrincipal;
现在在identity1中我只看到以下内容:
{http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: 12}
{http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: test@test.com}
{http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider: ASP.NET Identity}
{http://schemas.microsoft.com/ws/2008/06/identity/claims/role: Role1}
我的自定义UserData声明消失了。
更新 只想添加我的AuthenticationManager定义为:
HttpContext.GetOwinContext().Authentication;
更新 我已经解决了这个问题。在我的PasswordSignIn方法中,我不小心使用了ExtneralCookie身份验证类型,而不是使用ApplicationCookie:
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExtenralCookie);
到
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
答案 0 :(得分:0)
您可以尝试从当前线程中读取ClaimsIdentity,例如
/// <summary>
/// Gets authenticated identity
/// </summary>
private static ClaimsIdentity identity
{
get
{
return (ClaimsIdentity)Thread.CurrentPrincipal.Identity;
}
}
通过
阅读声明/// <summary>
/// gets authenticated UserId
/// </summary>
public static int UserId
{
get
{
return Convert.ToInt32(identity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).Select(c => c.Value).SingleOrDefault());
}
}
您必须获取UserDetail类型实例,因此需要反序列化声明值。