Often, in legacy Web applications, users authenticate themselves via a Web form. This Web form submits the user's credentials to business logic that determines their authorization level. Upon successful authentication, the application then submits a ticket in the form of a cookie, albeit a hard cookie or session variable. This ticket contains anything from just a valid session identification access token to customized personalization values.
ASP.NET encompasses and extends the very same logic described above into its architecture as an authentication facility, Forms Authentication. Forms Authentication is one of three authentication providers. Windows Authentication and Passport Authentication make up the other two providers. In this article, we will focus on Forms Authentication.
Forms Authentication is a system in which unauthenticated requests are redirected to a Web form where users are required to provide their credentials. Upon submitting the form, and being properly verified by your application, an authorization ticket is issued by your Web application in the form of a cookie. This authorization cookie contains the user's credentials or a key for reacquiring the user's identity (e.g. therefore making the identity persistent). In essence, Forms Authentication is a means for wrapping your Web application around your own login user interface and verification processes.
|
Related Reading
.NET Windows Forms in a Nutshell |
Let's take a look at the applicable settings to execute Forms Authentication. In general, setting up Forms Authentication involves just a few simple steps.
<configuration>
<system.web>
<authentication mode="Forms">
<forms name=".COOKIEDEMO"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/"/>
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
Upon setting the authentication
mode to Forms, you'll notice that we appended another child
element. The Forms element has five attributes that implement your forms
authentication configuration. The attributes and their descriptions are as
follows :
| Attribute | Description |
name |
This is the name of the HTTP cookie from which we will store our authentication ticket and information, respectively. |
loginURL |
This is the URL from which your unauthenticated client will be redirected. In most scenarios, this would be your login page, where the client is required to provide their credentials for authentication. |
protection |
This
is used to set the method from which to protect your cookie data.
The following valid values can be supplied:All: Specifies to use both data validation and encryption
to protect the cookie. Triple DES is used for encryption, if it is available and
if the key is long enough (48 bytes). The All value is the default (and
suggested) value.None: Used for sites that are only using cookies for
personalization and have weaker requirements for security. Both encryption
and validation can be disabled. This is the most efficient performance
wise, but must be used with caution.Encryption: Specifies that the cookie is encrypted using
Triple DES or DES, but data validation is not done on the cookie.
It's important to note that this type of cookie is subject to chosen
plaintext attacks.Validation: Specifies to avoid encrypting the
contents of the cookie, but validate that the cookie data has not been
altered in transit. To create the cookie, the validation key is
concatenated in a buffer with the cookie data and a MAC is
computed/appended to the outgoing cookie. |
timeout |
This
is the amount of time (in integer minutes) that the cookie has until it
expires. The default value for this attribute is 30 (thus expiring
the cookie in 30 minutes).The value specified is a sliding value, meaning that the cookie will expire n minutes from the time the last request was
received. |
path |
This
is the path to use for the issued cookie. The default value is set to "/"
to avoid issues with mismatched case in paths. This is because browsers
are case-sensitive when returning cookies. |
In our web.config
file, it's also important to note the value we have for the deny child element of the authorization section (as highlighted
below). Essentially, we set that value of the users attribute
to "?" to deny all anonymous users, thus redirecting unauthenticated
clients to the loginURL.
<configuration>
<system.web>
<authentication mode="Forms">
<forms name=".COOKIEDEMO"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/"/>
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
loginURL attribute discussed above). In this case, we should
save our login page as login.aspx. This is the page to where clients without
valid authentication cookie will be redirected. The client will complete
the HTML form and submit the values to the server. You can use the example
below as a prototype.
<%@ Import Namespace="System.Web.Security " %>
<html>
<script language="C#" runat=server>
void Login_Click(Object sender, EventArgs E)
{
// authenticate user: this sample accepts only one user with
// a name of username@domain.com and a password of 'password'
if ((UserEmail.Value == "username@domain.com") &&
(UserPass.Value == "password"))
{
FormsAuthentication.RedirectFromLoginPage(UserEmail.Value,
PersistCookie.Checked);
}
else
{
lblResults.Text = "Invalid Credentials: Please try again";
}
}
</script>
<body>
<form runat="server">
<h3>Login Page</h3>
<hr>
Email:<input id="UserEmail" type="text" runat="server"/>
<asp:RequiredFieldValidator ControlToValidate="UserEmail"
Display="Static"
ErrorMessage="*"
runat="server"/>
<p>Password:<input id="UserPass"
type="password"
runat="server"/>
<asp:RequiredFieldValidator ControlToValidate="UserPass"
Display="Static"
ErrorMessage="*"
runat="server"/>
<p>Persistent Cookie:<ASP:CheckBox id="PersistCookie"
runat="server" />
<p><asp:button id="cmdLogin"
text="Login"
OnClick="Login_Click"
runat="server"/>
<p><asp:Label id="lblResults"
ForeColor="red"
Font-Size="10"
runat="server" />
</form>
</body>
</html>
It's important to note that the
above page authenticates the client on the click event of the cmdLogin
button. Upon clicking, the logic determines if the username and password
provided match those hard-coded in the logic. If so, the client is redirected
to the requested resource. If not, the client is not authorized, and
thus receives a message depicting this.
You can adjust the logic to fit your needs, as it is very likely that you will
not have your usernames and passwords hard-coded into the logic. It is here at
the Login_Click function that you can substitute the logic with that of
your own. It is common practice to substitute database logic to verify the
credentials against a data table with a stored procedure.
You can also provide authorized credentials in the web.config file. Inside the forms section, you would append a user element(s), as follows :
<configuration>
<system.web>
<authentication mode="Forms">
<forms name=".COOKIEDEMO"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/">
<credentials passwordFormat="Clear">
<user name="user1" password="password1"/>
<user name="user2" password="password2"/>
<user name="user3" password="password3"/>
</credentials>
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
cmdLogin button discussed above.
Here is the code :
void Login_Click(Object sender, EventArgs E)
{
// authenticate user: this sample authenticates
// against users in your app domain's web.config file
if (FormsAuthentication.Authenticate(UserEmail.Value,
UserPass.Value))
{
FormsAuthentication.RedirectFromLoginPage(UserEmail.Value,
PersistCookie.Checked);
}
else
{
lblResults.Text = "Invalid Credentials: Please try again";
}
}
To enable forms authentication, cookies must be enabled on the client browser. If the client disables cookies, the cookie generated by Forms Authentication is lost and the client will not be able to authenticate.
In the next part of this series, we'll discuss how to incorporate Active Directory with Forms Authentication, to get that Windows OS layer of security without forcing the user to authenticate twice, once through your user interface and again through the Windows user interface.
Return to ONDotnet.com
Copyright © 2009 O'Reilly Media, Inc.