Search code examples
asp.netforms-authenticationverificationsessionid

Prevent visitors from opening certain pages


I have as ASP.Net 2.0 website with SQL Server as database and C# 2005 as the programming language. The website is almost complete and all the links are working fine. But I want to prevent normal users from opening a couple of pages. When any user clicks on those specific links, another page opens which contains a ASP Login control. The user has to supply a valid userid and password to display the links pointing to the restrictive pages. But being a newbie, I don't know how to leverage the full power of the ASP Login control. Because, if a user gets to know the exact url of the restricted pages, then he/she can bypass the login control and directly access those pages by typing the url into the address bar. I want to prevent this. If the user types the url directly in the address bar, I want that the page itself should check, whether the user has been validated through the Login control and either display the page or point the user to the Login page.

How do I implement this feature??

Thank You.

Lalit Kumar Barik


Solution

  • You should verify the user's logged in state at every Page_Load() event on pages that must control permissions, or simply put the authentication code in a CS file that will be included in all other files.

    Depending on the authentication architecture that you choose (simply use the session variable, or create a session id with cookies), you must adapt your code accordingly.

    The simplest way would be to manage log-ins through the session object. When the user logs in properly with the right credentials, you can set Session["logged_in"] = true. And on every Page_Load() event of the pages you want to protect, you'd need to do the following check.

    Add this code at the beginning of your Page_Load() function:

      if (Session["logged_in"] != null && (bool)Session["logged_in"] == true){
        Response.Write("I'm logged in!");
      }else{
        Response.Write("I'm not logged in.");
      }
    

    Please keep in mind that this is okay for simple intranet applications, but if you want to get into more secure login architectures, read up more about the subject, as reloying solely on session variables isn't safe because sessions can be highjacked.