How can I have ASP.NET automatically redirect non-logged in Forms users to the login page?

I found the answer.

Question: How do I automatically redirect non-logged in users to the login page?
Answer: Deny anonymous users access


Longer Explanation

In order to automatically redirect non-logged in users to login page, you need to deny anonymous access to "all" pages. This is done in the site's web.config file:

web.config

<?xml version="1.0"?>
<configuration>
   <system.web>
      ...
      <authorization>
         <deny users="?"/>
      </authorization>
   </system.web>
</configuration>

The special ? token is used to represent anonymous users.

This, when combined with telling Forms authentication where the "Login" page is:

<?xml version="1.0"?>
<configuration>
   <system.web>
      ...
      <authentication mode="Forms">
         <forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
      </authentication>
      <authorization>
         <deny users="?"/>
      </authorization>
   </system.web>
</configuration>

means that any any anonymous users will be automatically redirected to the login page.


A question that seems to never have been asked before gets answered, and everybody lives.


If you wish to force for all pages all used to be first logged in, you can capture the authentication request on global.asax and make this programmatically as:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    // This is the page
    string cTheFile = HttpContext.Current.Request.Path;

    // Check if I am all ready on login page to avoid crash
    if (!cTheFile.EndsWith("login.aspx"))
    {
        // Extract the form's authentication cookie
        string cookieName = FormsAuthentication.FormsCookieName;
        HttpCookie authCookie = Context.Request.Cookies[cookieName];

        // If not logged in
        if (null == authCookie)
        // Alternative way of checking:
        //     if (HttpContext.Current.User == null || HttpContext.Current.User.Identity == null || !HttpContext.Current.User.Identity.IsAuthenticated)
        {
            Response.Redirect("/login.aspx", true);
            Response.End();
            return;
        }
    }
}

This code is called on every page and checks all pages on your site.

Tags:

Asp.Net