2017-08-01 74 views
0

我加入GenerateUserIdentityAsync方法的要求:若权利要求可

public class ApplicationUser : IdentityUser 
{ 
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
    { 
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 

      userIdentity.AddClaim(new Claim(ClaimsStaticStrings.Inactivity, company.Inactivity.ToString())); 

     return userIdentity; 
    } 
} 

然后我设法得到它在账户/登录方法:

[HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) 
    { 
     var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false); 
     switch (result) 
     { 
      case SignInStatus.Success: 
       int inactivity = Utils.GetInactivityFromIdentity(User.Identity); 
       Response.Cookies.Add(new HttpCookie("inactivity", inactivity.ToString())); 

       return RedirectToAction("Index", "Home"); 
     } 
    } 


    public static int GetInactivityFromIdentity(IIdentity identity) 
    { 
     System.Security.Claims.ClaimsIdentity claims = (System.Security.Claims.ClaimsIdentity)identity; 

     var claim = claims.FindFirst(Models.ClaimsStaticStrings.Inactivity); 

     if (claim != null) 
     { 
      return int.Parse(claim.Value); 
     } 
     else 
      throw new Exception("Inactivity is not set"); 

    } 

它会抛出异常“活动是没有设置” 。变量“索赔”只有一个索赔 - 名称

但是,当我从任何其他页面(重定向后)调用GetInactivityFromIdentity方法 - 它工作正常(和索赔充满所有设置的索赔)。为什么这样?

回答

1

权利要求被序列化为AUTH-cookie中。 cookie不会设置直到哟经过重新加载页面上的身份验证。在您尝试从cookie访问索赔的点,有在HTTP请求没有Cookie - SignInManager将设置cookie只有当请求完成,而不是之后。你确实需要重定向/页面重载周期以获取Cookie,并要求提供。

你必须当您登录用户某种方式得到inactivity值不通过要求,但是从你的数据存储。