C# – ASP.NET – Checking if request is authenticated in master page

asp.netauthenticationcforms-authentication

In my master page's Page_Load event, I have the following code:

if(!Request.IsAuthenticated)
{
   FormsAuthentication.RedirectToLoginPage();
} else 
{
   // Do something. Note: Any work here gets performed when request is authenticated.
}

However, when I load a content page (which uses the master) while not authenticated, I do not get redirected to the login page. To get the desired behavior, I also need to add the above check in the Page_Load event in my content page.

Not a huge issue but is just annoying having the above check in every content page.

So I am curious, what is the reason for the master page not redirecting to login page when request isn't authenticated?

Best Answer

If all you want is FormsAuthentication to redirect to login page, when user has not logged in why don't you use config file to do this?

<system.web>
  <authorization>
    <deny users="?" />
  </authorization>
</system.web>

This should automatically send all 'anonymous' users to the configured login page for FormAuth.