title: Best practices for redirect to login page if session expired
body: <p>I want to redirect the user to login page, if session expired. I found many ways to do this but what is the best (or default) way in ASP.Net MVC5 with OWIN?
  Probably it works out of the box? But How?</p>
  
  <p>Razor:</p>
  
  <ul>
  <li>set a session variable after valid login </li>
  <li>add this in _Layout.cshtml:</li>
  </ul>
  
  <pre class="lang-cs prettyprint-override"><code>@if (Session["IsLogin"] == null)
  {
      Session.Abandon();
      Response.Redirect("~/LoginControllerName/LoginActionName");
  }
  </code></pre>
  
  <p>Global.asax:</p>
  
  <ul>
  <li>It is possible to use these two methods but I don't know how.</li>
  </ul>
  
  <pre class="lang-cs prettyprint-override"><code>protected void Session_Start(object sender, EventArgs e)
  {
      // Code that runs when a new session is started
  }
  
  protected void Session_End(object sender, EventArgs e)
  {
      // Code that runs when a session is expired
  }
  </code></pre>
  
  <p>My current solution:</p>
  
  <ul>
  <li>all controller inherit from <code>BaseController</code></li>
  <li>I used the OnAuthorizationAttribute because redirected should only be executed if it is a non-public page.</li>
  </ul>
  
  <pre class="lang-cs prettyprint-override"><code>public abstract class BaseController : Controller
  {
      protected override void OnAuthorization(AuthorizationContext filterContext)
      {
          if (this.Session["RedirectAfterLogin"] == null)
          {
              var isAnonymousAllowed = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
              if (!isAnonymousAllowed)
              {
                  this.Session["RedirectAfterLogin"] = this.Request.Url?.ToString();
                  filterContext.Result = this.RedirectToAction("LoginActionName", "LoginControllerName");
              }
          }
          base.OnAuthorization(filterContext);
      }
  }
  </code></pre>
  
  <ul>
  <li>After Redirect sign out the user:</li>
  </ul>
  
  <pre class="lang-cs prettyprint-override"><code>if (this.AuthenticationManager == null)
  {
      this.SetAuthenticationManager(this.HttpContext?.GetOwinContext()?.Authentication);
  }
  
  this.AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
  </code></pre>
  
  <ul>
  <li>After valid login set session variable:</li>
  </ul>
  
  <pre class="lang-cs prettyprint-override"><code>this.Session["RedirectAfterLogin"] = this.Request.Url?.ToString();
  </code></pre>