有理赔时 [英] When claims are available

查看:73
本文介绍了有理赔时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在GenerateUserIdentityAsync方法中添加了一个声明:

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

    }

它引发异常未设置不活动".变量"claims"只有一个声明-名称

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

但是,当我从任何其他页面调用GetInactivityFromIdentity方法时(重定向后),它都可以正常工作(并且声明被所有已设置的声明填充).为什么这样?

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?

推荐答案

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

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.

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

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

这篇关于有理赔时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆