When claims are available

对着背影说爱祢 提交于 2019-12-13 08:52:13

问题


I add a claim in GenerateUserIdentityAsync method:

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;
    }
}

Then I try to get it in Account/Login method:

    [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");

    }

it throws exception "Inactivity is not set". variable 'claims' has only one claim - name

But when I call GetInactivityFromIdentity method from any other page (after redirect) - it works fine (and claims are filled with all set claims). Why so?


回答1:


Claims are serialised into auth-cookie. Cookie is not set until yo go through page reload on authentication. At the point where you try to access the claims from the cookie, there is no cookie in HTTP Request - SignInManager will be setting the cookie only when the request is complete, but not immediately after. You indeed need a redirect/page reload cycle to get the cookie and claim available.

You'll have to somehow get inactivity value not through the claim, but from your data storage when you sign-in users.



来源:https://stackoverflow.com/questions/45449039/when-claims-are-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!