How to restrict access to all application pages in C#

Web developer follows the approach described in the article, when he/she has to restrict access to the pages of his/her application to authorized users only. In this case Web developer should change the web.config settings of his/her application to specify Forms authentication, and then create an .aspx login page to collect user credentials and complete the authentication check.

Web developer should modify web.config as follows:

    • Set the mode attribute of the <authentication> element to Forms.
    • Add a <forms> child element to the <authentication> element to specify key aspects of the Forms implementation:

      <authentication mode=”Forms”>

      <forms name=”.MyFormName”

      loginUrl=”Login.aspx”

      protection=”All”

      timeout=”30″

      path=”/”>

      </forms>

      </authentication>

       

      The next table presents different elements and their descriptions

       

      Element name

      Description

      name

      Defines the name of the HTTP cookie used by ASP.NET to maintain the user authentication information. Care should be taken when naming the cookie, because if two applications on the same server use the same cookie name, “cross authentication” could occur.

      loginUrl

      Defines the page to which ASP.NET will redirect users when they attempt to access pages in your application without being logged in. The login page should provide the fields required to authenticate the user, typically a login ID and password or whatever else the  application requires.

      protection

      Defines the protection method used for the cookie. Possible values are:

      -All- specifies that data validation and encryption will be used

      -Encryption- specifies that the cookie is encrypted

      -None- specifies no protection will be provided for the cookie information.

      -Validation- specifies that the cookie data will be validated to ensure it was not altered in transit

      The default is All and is highly recommended because it offers the highest level of protection for this authentication cookie.

      timeout

       

      Defines the amount of time in minutes before the cookie expires. The value provided here should be at least as long at the timeout for the session. Making the value shorter than the session timeout can result in a user being redirected to the page defined by the loginUrl before the session times out.

      path

      Defines the path of cookies issued by the application. Be aware that most browsers treat the path as case-sensitive and will not return the cookie for a request that does not match the value provided for the path attribute. The result will be having the users redirected as if they were not logged in. Unless your application requires specifying the path, we recommend that you leave the path as “/”.

       

       

      • Add <deny> and <allow> child elements to the <authorization> element to deny access to anonymous users and allow access to all who have been authenticated:

        <authorization>

        <deny users=”?” />  <!– Deny anonymous users –>

        <allow users=”*” /> <!– Allow all authenticated users –>

        </authorization>

        In the .aspx file for the login page Web develop should:

        1. Add the fields required to collect the data the application needs to authenticate the user. Most applications require, at a minimum, a user login ID and password, but Web developer can specify whatever his/her application requires.
        2. Add a Login button
        3. (Optional) Include a checkbox for users to indicate that they want to be remembered between sessions. (Web developer will need to add some code to the code-behind class to persist the authentication cookie on the client machine.)

        In the code-behind class for the login page, use the .NET language of Web developer choices to:

        1. Use the Login button click event to verify the user credentials
        2. If the user credentials are valid, create a Forms authentication cookie and add it to the cookie collection returned to the browser by calling the SetAuthCookie method of the FormsAuthentication class
        3. (Optional) Set the Forms authentication cookie to be persisted on the client machine.
        4. Redirect the user to the appropriate application start page using Response.Redirect.

         

        The next code illustrates the idea:

        Web.config file

        <?xml version=”1.0″?>

        <configuration xmlns:xdt=”http://schemas.microsoft.com/XML-Document-Transform”>

        <connectionStrings>

        <add name=”myDB”

        connectionString=”Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True”

        xdt:Transform=”SetAttributes” xdt:Locator=”Match(name)”/>

        <add name=”DBConnectionString” connectionString=”LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;Initial Catalog=AspNetDB”

        providerName=”System.Data.SqlClient” />

        </connectionStrings>

        <system.web>

        <authentication mode=”Forms”>

        <forms name=”.RestrictAccessToAllPages”

        loginUrl=”LoginPage.aspx”

        protection=”All”

        timeout=”30″

        path=”/”>

        </forms>

        </authentication>

        <authorization>

        <deny users=”?” />

        <!– Deny anonymous user –>

        <allow users=”*” />

        <!– Allow all authenticated users –>

        </authorization>

        </system.web>

        </configuration>

        LoginPage.aspx Page

        <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”LoginPage.aspx.cs” Inherits=”RestrictAccessToAllPages.LoginPage” %>

        <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

        <html xmlns=”http://www.w3.org/1999/xhtml”>

        <head runat=”server”>

        <title></title>

        </head>

        <body>

        <form id=”frmSecurity” method=”post” runat=”server”>

        <table width=”100%” cellpadding=”0″ cellspacing=”0″ border=”0″>

        <tr>

        <td align=”center”>

        </td>

        </tr>

        <tr>

        <td>

        </td>

        </tr>

        </table>

        <table width=”90%” align=”center” border=”0″>

        <tr>

        <td>

        </td>

        </tr>

        <tr>

        <td align=”center” class=”PageHeading”>

        Block Access To All Pages (C#)

        </td>

        </tr>

        <tr>

        <td>

        </td>

        </tr>

        <tr>

        <td align=”center”>

        <table>

        <tr>

        <td class=”LabelText”>

        Login ID:

        </td>

        <td>

        <asp:TextBox ID=”txtLoginID” runat=”server” />

        </td>

        </tr>

        <tr>

        <td class=”LabelText”>

        Password:

        </td>

        <td>

        <asp:TextBox ID=”txtPassword” runat=”server” TextMode=”Password” />

        </td>

        </tr>

        <tr>

        <td colspan=”2″ align=”center”>

        <asp:CheckBox ID=”chkRememberMe” runat=”server” Text=”Remember Me” />

        </td>

        </tr>

        <tr>

        <td colspan=”2″ align=”center”>

        <br />

        <input id=”btnLogin” runat=”server” type=”button” value=”Login” />

        </td>

        </tr>

        <tr>

        <td colspan=”2″ align=”center”>

        <br />

        <input type=”button” value=”Attempt Access without Login” onclick=”document.location=’Default.aspx'” />

        </td>

        </tr>

        </table>

        </td>

        </tr>

        </table>

        </form>

        </body>

        </html>

        Code behind (.cs)

        using System;

        using System.Collections.Generic;

        using System.Linq;

        using System.Web;

        using System.Web.UI;

        using System.Configuration;

        using System.Data;

        using System.Data.OleDb;

        using System.Web.Security;

        using System.Web.UI.WebControls;

        using System.Web.UI.HtmlControls;

         

        namespace RestrictAccessToAllPages

        {

        public partial class LoginPage : System.Web.UI.Page

        {

        protected void Page_Load(object sender, EventArgs e)

        {

        this.btnLogin.ServerClick += new EventHandler(this.btnLogin_ServerClick);

        }

        // Retrieves a connection string by name.

        // Returns null if the name is not found.

        static string GetConnectionStringByName(string name)

        {

        // Assume failure.

        string returnValue = null;

         

        // Look for the name in the connectionStrings section.

        ConnectionStringSettings settings =

        ConfigurationManager.ConnectionStrings[name];

         

        // If found, return the connection string.

        if (settings != null)

        returnValue = settings.ConnectionString;

         

        return returnValue;

        }

        private void btnLogin_ServerClick(Object sender, System.EventArgs e)

        {

        // name of querystring parameter containing return URL

        const String QS_RETURN_URL = “ReturnURL”;

        OleDbConnection dbConn = null;

        OleDbCommand dCmd = null;

        OleDbDataReader dr = null;

        String strConnection = null;

        String strSQL = null;

        String nextPage = null;

        try

        {

        // get the connection string from web.config and open a connection

        // to the database

         

        strConnection = GetConnectionStringByName(“DBConnectionString”);

         

        dbConn = new OleDbConnection(strConnection);

        dbConn.Open();

        // check to see if the user exists in the database

        strSQL = “SELECT (FirstName + ‘ ‘ + LastName) AS UserName ” +

        “FROM AppUser ” +

        “WHERE LoginID=? AND ” +

        “Password=?”;

        dCmd = new OleDbCommand(strSQL, dbConn);

        dCmd.Parameters.Add(new OleDbParameter(“LoginID”,

        txtLoginID.Text));

        dCmd.Parameters.Add(new OleDbParameter(“Password”,

        txtPassword.Text));

        dr = dCmd.ExecuteReader();

        if (dr.Read())

        {

        // user credentials were found in the database so notify the system

        // that the user is authenticated

        FormsAuthentication.SetAuthCookie((String)(dr[“UserName”]),

        chkRememberMe.Checked);

        // get the next page for the user

        if (Request.QueryString[QS_RETURN_URL] != null)

        {

        // user attempted to access a page without logging in so redirect

        // them to their originally requested page

        nextPage = Request.QueryString[QS_RETURN_URL];

        }

        else

        {

        // user came straight to the login page so just send them to the

        // home page

        nextPage = “Default.aspx”;

        }

        // Redirect user to the next page

        // NOTE: This must be a Response.Redirect to write the cookie to

        //       the user’s browser.  Do NOT change to Server.Transfer

        //       which does not cause around trip to the client browser

        //       and thus will not write the authentication cookie to the

        //       client browser.

        Response.Redirect(nextPage, true);

        }

        else

        {

        // user credentials do not exist in the database – in a production

        //application this should output an error message telling the user

        // that the login ID or password was incorrect.

        }

        }  // try

        finally

        {

        // cleanup

        if (dr != null)

        {

        dr.Close();

        }

        if (dbConn != null)

        {

        dbConn.Close();

        }

        }  // finally

        }

        }

        }