当索赔可用时

时间:2017-08-01 23:17:03

标签: c# asp.net-identity claims-based-identity claims

我在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");

    }

它抛出异常&#34;未设置不活动&#34;。变量&#39;声明&#39;只有一个声明 - 名称

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

1 个答案:

答案 0 :(得分:1)

声明被序列化为auth-cookie。在您通过身份验证重新加载之前,Cookie不会设置。当您尝试从cookie访问声明时,HTTP请求中没有cookie - SignInManager将仅在请求完成时设置cookie,但不会立即设置cookie。您确实需要一个重定向/页面重新加载周期来获取cookie和声明。

您必须以某种方式获取inactivity值不是通过声明,而是在您登录用户时从您的数据存储中获取。