Problem with Losing Session State and User.Identity.IsAuthenticated

Discussion in 'ASP.NET / ASP.NET Core' started by Miguel Ribeiro, Jun 23, 2016.

  1. Hi,

    I have an issue where my session state as well as the authentication cookie from Asp.Net Identity constantly gets lost.

    It follows no pattern or has any consistency as to when or how it happens, only that it's happening a lot on my live site. On my dev environment I don't experience this. My users are constantly being kicked off at different places on the site so can't narrow it down to a specific page/controller/action etc.

    I store an object in session state and use an ActionFilter (onactionexecuting) for my secured controllers/actions to retrieve this object out of session on each request to my secured controllers.

    What I'm not understanding is if the session goes 'missing' I check for the Authentication Cookie (filterContext.HttpContext.User.Identity) and use that to reload the session. BUT, this also goes 'missing' and I get a false when doing the check for filterContext.HttpContext.User.Identity.

    I can see the Authentication Cookie getting sent as part of the request just before the session gets lost and I'm kicked out so I'm not sure how this mechanism works exactly, it would seem it works the same as the Session state and that the server has also lost this Authentication bit on its' side.

    This is my action filter:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
    SecuredController baseController = filterContext.Controller as SecuredController;

    // Check if the session is available
    if (filterContext.HttpContext.Session["UserSession"] == null)
    {

    if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
    {
    if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
    {
    filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
    filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    filterContext.Result = new JsonResult
    {
    Data = new { Error = "Unavailable", Url = "~/Account/Login" },
    JsonRequestBehavior = JsonRequestBehavior.AllowGet
    };
    return;
    }
    if (!string.IsNullOrEmpty(HttpContext.Current.Request.RawUrl))
    {
    string returnUrl = HttpUtility.UrlEncode(HttpContext.Current.Request.RawUrl);
    HttpContext.Current.Response.Redirect("~/Account/Login?returnUrl=" + returnUrl);
    }
    else
    {
    HttpContext.Current.Response.Redirect("~/Account/Login");
    }
    }

    string userId = filterContext.HttpContext.User.Identity.GetUserId();

    Web.Helpers.Common common = new Helpers.Common();
    UserSession userSession = common.GetUserSession(userId);

    filterContext.HttpContext.Session["UserSession"] = userSession;
    }

    // Set the Current user to the session variable
    baseController.CurrentUser = (UserSession)filterContext.HttpContext.Session["UserSession"];

    // Continue executing the relevant action
    base.OnActionExecuting(filterContext);
    }
    and here's my ConfigureAuth

    public void ConfigureAuth(IAppBuilder app)
    {
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),

    SlidingExpiration =true,
    });
    }
    I also have some IIS rules so that users always use the full domain name

    <rules>
    <rule name="Add www prefix to example.com domain" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
    <add input="{HTTP_HOST}" pattern="^example\.com" />
    </conditions>
    <action type="Redirect" url="http://www.example.com/{R:1}" />
    </rule>
    </rules>
    and I'm not sure if this is having an impact with the cookie, though once the user is on the 'inside' the url is always the full domain name, so don't know if this is an issue.

    Any help would be greatly appreciated
     
  2. RayH

    RayH DiscountASP.NET Lackey DiscountASP.NET Staff

    Your application pool is probably getting recycled, so "InProc" won't work for you. You'll need to switch to SQL Server Session State.
     
    mjp likes this.

Share This Page