OnValidateIdentity 会话为空 - Mvc Owin

Qua*_*ong 4 asp.net-mvc identity owin asp.net-mvc-5 asp.net-identity

目前,我在 OnValidateIdentity 中访问 Session 时遇到问题 -HttpContext.Current.Session为空。怎么了?我的申请如下:

  • 我有 2 个项目:Mvc vs WebApi

我希望用户在我更改密码时注销 -> 更改安全标记。我实现为:当用户请求时,Mvc 项目将验证 SecurityStamp 更改。我将从其他 webapi 网站获取 SecurityStamp。这意味着我的 mvc 不能通过 webapi 直接访问数据库。而且我必须在授权标头中输入令牌才能从 webapi 获取 securitystamp。但是,我无法从 session 访问令牌,当我成功登录时,我将令牌存储在 Session 中。代码示例:

public void ConfigureAuthentication(IAppBuilder app)
    {            
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            CookieSecure = CookieSecureOption.SameAsRequest,
            LoginPath = new PathString("/Home"),
            LogoutPath = new PathString("/Account/Logout"),
            ExpireTimeSpan = TimeSpan.FromMinutes(30),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = async ctx =>
                {
                    var claim = ctx.Identity.FindFirst("SecurityStamp");
                    var accessToken = HttpContext.Current.Session["token"].ToString();

                    using (HttpClient httpClient = new HttpClient())
                    {
                        // Used accessToken variable for httpClient
                        // TODO Get security stamp from webapi . Ex :
                        string securityStampWebApi = "demo";
                        if (securityStampWebApi != claim.Value)
                        {
                            ctx.RejectIdentity();
                        }
                    }
                }
            }
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    }
Run Code Online (Sandbox Code Playgroud)

建议其他实现我可以完成这个案例。

Sho*_*eel 5

cookie 中间件在 IIS 管道中的身份验证阶段运行,该阶段在HttpContext会话状态可用之前。所以你需要在没有它的情况下工作。