OnValidateIdentity session is null - Mvc Owin

2019-07-01 13:52发布

问题:

Currently, I have problems when access Session in OnValidateIdentity - HttpContext.Current.Session is null. What's I wrong . My application as below: - I have 2 project : Mvc vs WebApi - I want user will logout when I changed password -> change security stamp. - I implement as: The Mvc Project will validate SecurityStamp changed when user request. And I'm will get SecurityStamp from other webapi website . This mean My mvc not access directly to database that through out webapi. And I'm must be input token in authorize header to get securitystamp from webapi. But, I can't access token from session , when I login successfully I stored the token in the Session. Code example:

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

suggestion other implementaion to I can finish this case.

回答1:

The cookie middleware runs at the authenticate stage in the IIS pipeline, which is prior to HttpContextor session state being made available. So you will need to work without it.



回答2:

You should not be using HttpContext.Current in OWIN callbacks in general, that is most likely the issue. You should flow in the context provided to the callback.