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:
- 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.
- Add a Login button
- (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:
- Use the Login button click event to verify the user credentials
- 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
- (Optional) Set the Forms authentication cookie to be persisted on the client machine.
- 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″?>
<!–
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
–>
<configuration>
<connectionStrings>
<add name=”ApplicationServices”
connectionString=”data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true”
providerName=”System.Data.SqlClient” />
<add name=”DBConnectionString” connectionString=”LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;Initial Catalog=AspNetDB”
providerName=”System.Data.SqlClient” />
</connectionStrings>
<system.web>
<compilation debug=”true” strict=”false” explicit=”true” targetFramework=”4.0″ />
<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>
<membership>
<providers>
<clear/>
<add name=”AspNetSqlMembershipProvider” type=”System.Web.Security.SqlMembershipProvider” connectionStringName=”ApplicationServices”
enablePasswordRetrieval=”false” enablePasswordReset=”true” requiresQuestionAndAnswer=”false” requiresUniqueEmail=”false”
maxInvalidPasswordAttempts=”5″ minRequiredPasswordLength=”6″ minRequiredNonalphanumericCharacters=”0″ passwordAttemptWindow=”10″
applicationName=”/” />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name=”AspNetSqlProfileProvider” type=”System.Web.Profile.SqlProfileProvider” connectionStringName=”ApplicationServices” applicationName=”/”/>
</providers>
</profile>
<roleManager enabled=”false”>
<providers>
<clear/>
<add name=”AspNetSqlRoleProvider” type=”System.Web.Security.SqlRoleProvider” connectionStringName=”ApplicationServices” applicationName=”/” />
<add name=”AspNetWindowsTokenRoleProvider” type=”System.Web.Security.WindowsTokenRoleProvider” applicationName=”/” />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests=”true”/>
</system.webServer>
</configuration>
LoginPage.apsx Page
<%@ Page Language=”vb” AutoEventWireup=”false” CodeBehind=”LoginPage.aspx.vb” Inherits=”RestrictAccessToAllPagesVB.LoginPage” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”https://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 (.vb)
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Configuration
Imports System.Data
Imports System.Data.OleDb
Imports System.Web.Security
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Namespace RestrictAccessToAllPages
Public Class LoginPage
Inherits System.Web.UI.Page
‘controls on the form
Protected txtLoginID As TextBox
Protected txtPassword As TextBox
Protected chkRememberMe As CheckBox
Protected WithEvents btnLogin As HtmlInputButton
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
‘ Retrieves a connection string by name.
‘ Returns null if the name is not found.
Private Function GetConnectionStringByName(ByVal name As String) As String
‘ Assume failure.
Dim returnValue As String = Nothing
‘ Look for the name in the connectionStrings section.
Dim settings As ConnectionStringSettings =
ConfigurationManager.ConnectionStrings(name)
‘ If found, return the connection string.
If Not IsNothing(settings) Then
returnValue = settings.ConnectionString
End If
GetConnectionStringByName = returnValue
End Function
Private Sub btnLogin_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLogin.ServerClick
‘name of querystring parameter containing return URL
Const QS_RETURN_URL As String = “ReturnURL”
Dim dbConn As OleDbConnection
Dim dCmd As OleDbCommand
Dim dr As OleDbDataReader
Dim strConnection As String
Dim strSQL As String
Dim nextPage As String
Try
‘get the connection string from web.config
‘and open a connection to the database
strConnection = GetConnectionStringByName(“DBConnectionString”)
dbConn = New OleDb.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()) Then
‘user credentials were found in the database so notify
‘the(System) that the user is authenticated
FormsAuthentication.SetAuthCookie(CStr(dr.Item(“UserName”)), chkRememberMe.Checked)
‘get the next page for the user
If (Not IsNothing(Request.QueryString(QS_RETURN_URL))) Then
‘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”
End If
‘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
End If
Finally
‘cleanup
If (Not IsNothing(dr)) Then
dr.Close()
End If
If (Not IsNothing(dbConn)) Then
dbConn.Close()
End If
End Try
End Sub
End Class
End Namespace