【问题标题】:OnValidateIdentity session is null - Mvc OwinOnValidateIdentity 会话为空 - Mvc Owin
【发布时间】:2014-07-06 07:40:09
【问题描述】:

目前,我在 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);
    }

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

【问题讨论】:

  • 任何不使用 Session 的替代解决方案?

标签: asp.net-mvc asp.net-mvc-5 identity asp.net-identity owin


【解决方案1】:

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

【讨论】:

  • In OnResponseSignIn HttpContext.Currentnot null,但HttpContext.Current.SessionNull。代码:Provider = new CookieAuthenticationProvider() { OnResponseSignIn
  • IIS 管道中的所有阶段,使用OWIN中间件?
【解决方案2】:

一般来说,您不应该在 OWIN 回调中使用 HttpContext.Current,这很可能是问题所在。您应该在提供给回调的上下文中流动。

【讨论】:

    猜你喜欢
    • 2014-08-12
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    相关资源
    最近更新 更多