As you have probably deduced, forms authentication requires a form. Add a second web form, Login.aspx, to the project. For now, just place a single button, btnAuthenticate, on the form. Add a using statement for System.Web.Security at the top of the form's module, and then the code for this button to call::
private void btnAuthenticate_Click(object sender, System.EventArgs e)
{
FormsAuthentication.RedirectFromLoginPage("Mike", false);
}
You'll also need to make some changes to the Web.config file to tell ASP.NET to use forms authentication with this particular application. First, replace the existing authentication section:
<authentication mode="Forms">
<forms name="SampleAuth"
loginUrl="Login.aspx"
slidingExpiration="true">
</forms>
</authentication>
That configuration section tells ASP.NET to use forms authentication, and to create a cookie named SampleAuth to store information on the user's computer. The loginUrl attribute indicates the form that should be used for authentication, and the slidingExpiration attribute resets the expiration time of the cookie each time the application gets a request from the user (by default, sessions expire in 30 minutes).
You'll also need to modify the authorization section of the Web.config file:
<authorization>
<deny users="?" />
</authorization>
By default, the authorization section in the Web.config file allows all users access to the entire application. With this change, it explicitly denies access for unauthenticated users.
Run the application again, and instead of Default.aspx, you'll see Login.aspx. Click the button, and the application will redirect you back to Default.aspx, where the label will show the name of the authenticated user. The sequence of events goes like this:
The user requests Default.aspx.
ASP.NET notes that the application uses forms authentication and that the user has not yet been authenticated, so it redirects to Login.aspx.
When the user clicks the button, the code uses the FormsAuthentication.RedirectFromLoginPage method. This method announces to ASP.NET that you're satisfied with this user's credentials. The first parameter to the method is the name to assign to the user, and the second is a Boolean value that indicates whether a permanent cookie should be saved on the user's hard drive.
ASP.NET knows that the user was originally trying to load Default.aspx, so that's the page that it redirects to, in this case.
The identity of the now-authenticated user is available to any code that needs it.
Some of the Fiddly Bits
You can control the behavior of the forms authentication engine somewhat by the attributes that you supply for the <forms> element in the Web.config file. Here are the attributes that you can use for this element:
Attribute Purpose
loginUrl Name of the web form to send all unauthenticated requests to. This defaults to Default.aspx.
name Name of the cookie to use to store the authenticated identity. This defaults to .ASPXAUTH. If there are multiple applications on your server using forms authentication, and you leave this set to the default, then they'll all share the same cookie. That's a problem if they don't all have the same authentication requirements. I recommend always setting this to a unique value for each application.
path Path where the cookie will be stored. Defaults to a single slash.
protection Specifies the verification method to use to prevent cookie spoofing: None, Encryption (encrypts but doesn't validate the cookie), Validation (adds a validation key to the cookie), and All (the default, which both encrypts and validates the cookie). Unless your web server is extremely overloaded, leave this at the default value of All.
requiresSSL A Boolean value that determines whether ASP.NET demands an SSL connection for the cookie. The default is false.
slidingExpiration Specifies whether the cookie times out at a fixed point after the initial authentication (false, which is the default), or whether the timeout is reset with each request (true).
timeout The number of minutes it takes for the cookie to expire. The default is 30. For permanent cookies, this attribute is ignored.
A Little More Realism, Please
So far, my forms-based authentication isn't really doing much authenticating; anyone who can click a button has access to the entire application. It's up to you to decide just how you want to authenticate users of your application, and to supply custom code to fit your scheme. A typical scheme might require users to type in a username and a password on the login page. To support this, add two TextBox controls, txtUsername and txtPassword, to the Login.aspx page. Now you can alter the code to distinguish between different users:
void btnAuthenticate_Click(object sender, EventArgs e) {
if(txtUserName.Text == "Mike" &&
txtPassword.Text == "Soup") {
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,
false);
}
if(txtUserName.Text == "Adam" &&
txtPassword.Text == "Dinosaur") {
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,
false);
}
}
Now you'll find that if you submit a proper combination of username and password, you still end up on Default.aspx, and it knows which user you logged in as. If you submit an invalid combination, the call to FormsAuthentication.RedirectFromLoginPage will never happen, and the browser will just reload Login.aspx. Of course, hard-wiring usernames and passwords directly into your source code is a pretty horrible idea; it means you have to modify the source code every time your user list changes. In a real application, you'd typically check against a database or XML file of users, which can be modified more easily at runtime. But the authentication engine doesn't care; you can use whatever scheme you like to decide whether users are legitimate.