17

I have an ASP.NET website.

I want users who are not logged in to be automatically (re)directed to the login page, for example,

~/Account/Login.aspx

As it is now, users are able to visit pages (for example, default.aspx) without being logged in.


Note: I am operating on the (perhaps incorrect) assumption that ASP.NET has its own authentication cycle that happens behind my back before every (and any) page loads.


Update @asawyer provided a link that, while not helping to answer the question, did provide a pretty graphic:

Enter image description here

Well, what have you tried?

I have a web.config file that enables Forms authentication:

<?xml version="1.0"?>
...
<configuration>
   ...
   <system.web>
      <authentication mode="Forms">
         <forms loginUrl="~/Account/Login.aspx" name=".ASPXFORMSAUTH" slidingExpiration="true"/>
      </authentication>
      ...
   </system.web>
   ...
</configuration>

When i browse to the "default" page, I am able to view it, for example,

GET http://localhost:53149/WebSite/ HTTP/1.1
Host: localhost:53149

And I'm get the page contents:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0

In other words, rather than being forced to login to the web-site, I am not being forced to log in to the web-site.

It might be related to the fact that my browser is running locally to the web-server; but I'm using Forms, not Windows (and not Passport and not None) authentication.

Bonus Reading

Community
  • 1
  • 1
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
  • 3
    http://www.asp.net/web-forms/tutorials/security – asawyer Jun 08 '12 at 20:22
  • @Jeremy i've been googling around for that for 2.5 hours now. Since nobody has the answer on Stackoverflow yet, i figured i would ask the question. Then hopefully i get can an answer. – Ian Boyd Jun 08 '12 at 20:27
  • 2
    Not sure how it doesn't help my friend, I have a hard time believing you've gone through all of that information in 3 minutes. – asawyer Jun 08 '12 at 20:28
  • 2
    Then start here: [ASP.NET Authentication](http://msdn.microsoft.com/en-us/library/aa291347(v=vs.71).aspx). In a nutshell, it involves deciding which authentication/security you wish to include and what tweaks (and how) to make in your web.config. – Jeremy Jun 08 '12 at 20:28
  • @asawyer And within that time span enriching the graphic (but no freehand circles). – Filburt Jun 08 '12 at 20:31
  • @asawyer There are 28 tutorials altogether. i'm not using the persistence infrastructre provided by **Forms**, that eliminates `Membership (10 Tutorials)`, `Roles (6 Tutorials)` and `Admin (6 Tutorials)`. Leaving 6 tutorials, which are all on one page. This page contains no C# code, and no XML (e.g. for adding to a web-config) file. – Ian Boyd Jun 08 '12 at 20:36
  • `not using the persistence infrastructre provided by Forms` Seems like this sort of information would have been useful upfront. My crystal ball is in the shop this week. Anywho, good news! [It's not to hard to write your own custom membership provider!](http://www.asp.net/web-forms/videos/how-do-i/how-do-i-create-a-custom-membership-provider) – asawyer Jun 08 '12 at 20:40
  • @asawyer In that case i should rephrase my question to: "*How can i have ASP.net automatically redirect non-logged in users to the login page?*". In fact, i thin i *will* change my title to that. – Ian Boyd Jun 08 '12 at 20:51
  • @IanBoyd Do you search for code to send all users, on any page, to login first ? am I right ? – Aristos Jun 08 '12 at 20:52
  • If your dead set on avoiding the built in membership providers, I've done this retrofitting a very old existing application. I added a master page and made everything a content page of it. Then the master page gets a load event on every page load. Check a session value representing "Is this person logged in" and if it doesn't exist, redirect to the login page. Oh, and don't do this check if the requested page **is** the login page. – asawyer Jun 08 '12 at 20:54
  • a user can have 25k and know many thinks about A, but not so many about B. With 25k have prove that help other on what he knows, and for me is good to get some help back in the part that did not know or fully understand. – Aristos Jun 08 '12 at 21:03
  • @Jeremy That is the answer. i beat you to the answer (spent the last 12 minutes composing it; while talking to co-workers about the radiation leak in Michigan last night). i'm ok with you copying-pasting my answer as your own and i'll accept it. – Ian Boyd Jun 08 '12 at 21:13
  • Thanks but your answer is much nicer! – Jeremy Jun 08 '12 at 21:16
  • If you are learning and collecting infos for the big picture: You may find the hint useful that there are (in 2015) three ways to force authentication: 1) webconfig.xml (there can be several files), 2) Attributes like `[Authorize]` and 3) hard coded checking and forwarding. About 2), see here: http://stackoverflow.com/questions/10848086/authorize-attribute-in-asp-net-mvc. (Not every constellation is handled in every tutorial.) Security: Attributes are compiled into MyApp.dll, webconfig.xml of course is not. – peter_the_oak Feb 12 '16 at 09:04

4 Answers4

29

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.

Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
  • 1
    +1 because you found the config way :) I am code too much and forget to see if they all ready made it on config.. – Aristos Jun 08 '12 at 21:14
  • @Aristos Well, the way in which you play nicely with Microsoft's carefully designed asp.net security system. But, my god, trying to find that by hunting around MSDN and the web - damned near impossible. In the end i stumbled across a ***second*** web-config automatically created by the Visual Studio, where they allow/deny particular files. Googling those keywords (`authorization allow deny ?`) brought me to [a link that mentions denying access to an entire site](http://weblogs.asp.net/gurusarkar/archive/2008/09/29/setting-authorization-rules-for-a-particular-page-or-folder-in-web-config.aspx). – Ian Boyd Jun 08 '12 at 21:18
  • 1
    @IanBoyd: I implemented the way you suggested, but after I login, it does not take me to the page which I mentioned to redirect after the succesful login. – Nad Nov 27 '14 at 15:55
  • the problem comes when you need to get access to registration form, which redirect you to login form again :) – Vasil Valchev Jul 01 '15 at 15:47
  • This (Q+A) was a hard digging work. Thank you very much! – peter_the_oak Feb 12 '16 at 07:39
3

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aristos
  • 66,005
  • 16
  • 114
  • 150
1

I know it's many years later, but if anyone finds themself here you may be missing this bit in the webconfig. Within the tag you need to add this:

<location path="SecurePage.aspx">
<system.web>
  <authorization>
    <deny users="?"/>
  </authorization>
</system.web>

This tells the site that SecurePage.aspx requries the user to be logged in. This is how I've been doing it for a few years now

0

Add this to you web.config

<system.web>
    // ...
    <authentication mode="Forms">
        <forms loginUrl="~/Account/Login.aspx" 
               name=".ASPXFORMSAUTH" 
               slidingExpiration="true" />
    </authentication>
</system.web>
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
  • 2
    The web-site comes with a snippit very similar to that "out of the box" (Yours includes a `name` and `slidingExpiration`, but loses the `Timeout`). Adding and removing attributes, i am still able to browse to `default.aspx` without being asked for a username/password (i.e. without being logged into the site) – Ian Boyd Jun 08 '12 at 20:38