The Forms Authentication Module
The FormsAuthenticationModule exposes forms-based authentication services to ASP.NET applications. The module allows you to optionally handle a FormsAuthentication_OnAuthentication event during the authentication process.
You must provide a logon URL that collects and authenticates credentials. If the credentials are valid, you can rely upon the provided helper utilities to redirect the request to the originally requested resource with an appropriate authentication ticket. Alternatively, you can simply get the form or set it, if you do not want the redirection. For more information about authentication tickets, see Creating a Forms Authentication Ticket.
In the simplest case, you can just configure a logon URL to redirect unauthenticated requests to a page, supply a minimal implementation of that file customized from an example page, and supply valid credential pairs, either in the Web.config file or in a separate file. The framework takes care of the rest. The following example code shows how this might be handled in an ASP.NET configuration [ Web.config ] file:
<authentication mode = "forms">
<forms forms = "401kApp"
loginurl = "/login.aspx"
decryptionkey = "1!#$$*13^">
<credentials passwordFormat=SHA1>
<user name = "Mary" password = "9611E4F94EC4972D5A537EA28C69F89AD28E5B36" />
<user name = "John" password = "BA7157A99DFE9DD70A94D89844A4B4993B10168F" />
</credentials>
</forms>
</authentication>
The FormsAuthenticationModule is configured by the <forms> element in a configuration file. The following table describes how to set the forms, decryptionkey, and loginurl attributes of the <forms> element
Attribute
Description
Forms
Name of the HTTP forms to use for the authentication ticket. By default, this value is .aspxauth.
Decryptionkey
Key used to decrypt authentication tickets. Note that the default is autogenerate, so a computer-specific key is used, and the form cannot be shared between servers. This key is stored in clear text.
Loginurl
URL to which the request is redirected if it does not contain a valid authentication ticket. This should be an SSL URL ( https:// ) to prevent credentials from being posted in clear text. However, it need not be SSL-protected if the logon form itself posts back to an SSL-protected resource.
Forms Authentication Control Flow The flow of control for a forms authentication conversation is shown in the following.
1. Client requests a protected resource from a server.
GET /default.aspx
Server redirects the request to a logon page to collect credentials if there is no authentication form. Information about the originating page is placed in the query string using RETURNURL as the key.
302 Found
Location: https://samples.microsoft.com/login.aspx?RETURNURL=/default.aspx
2. Client follows the redirection to the logon page.
GET /login.aspx?RETURNURL=/default.aspx
Server returns the logon page. ( Use SSL to protect the user's credentials from being sent in clear text, at least for the post back to the logon page. )
200 OK
3. User enters credentials into the logon form.
POST /login.aspx?RETURNURL=/default.aspx
Server validates user credentials and, if the credentials are authenticated, redirects the browser to the original URL retrieved from the logon ticket. The authentication ticket is issued as a cookie.
302 Found
Location: /default.aspx
4. Follows the redirection and requests the original resource again.
GET /default.aspx
Server grants access if the user is authorized and grants the authentication form, which contains an authentication ticket. Future requests by the same browser session will be authenticated when the module inspects the form. It is possible to create a durable form that can be used for future sessions, but only until the form's expiration date.
200 OK
Set-Cookie: ASPXTICKET=ABCDEFG12345; Path=/
Creating a Forms Authentication Ticket The authentication ticket is a linear representation of the FormsAuthenticationTicket class suitable for encoding as an HTTP form or query string.
To create an authentication ticket form from a FormsAuthenticationTicket class
Forms Authentication Credentials You can allow the FormsAuthenticationModule to handle the authentication process from an application configuration file. Valid user/password pairs can be placed in the <credentials> section of a configuration file. You can compare the credentials collected from the user requesting logon privileges to the list of user/password pairs in the <credentials> section to determine if access should be granted. In the following example, users Mary and John can log on if they provide the correct password:
<credentials passwordFormat = "SHA1" >
<user name = "Mary" password = "9611E4F94EC4972D5A537EA28C69F89AD28E5B36" />
<user name = "John" password = "BA7157A99DFE9DD70A94D89844A4B4993B10168F" />
</credentials>
Notice that the credential pairs must be contained within a <credentials> section, the password format is Secure Hash Algorithm-1 ( SHA1 ), the user names are in clear text, and the passwords are hashed using the SHA1 algorithm.
The passwordFormat attribute is required, and can be one of the values listed in the following table.
Value
Description
Clear
Passwords are stored in clear text. The user password is compared directly to this value without further transformation.
MD5
Passwords are stored using a Message Digest 5 ( MD5 ) hash digest. When credentials are validated, the user password is hashed using the MD5 algorithm and compared for equality with this value. The clear-text password is never stored or compared when using this value. This algorithm produces better performance than SHA1.
SHA1
Passwords are stored using the SHA1 hash digest. When credentials are validated, the user password is hashed using the SHA1 algorithm and compared for equality with this value. The clear-text password is never stored or compared when using this value. Use this algorithm for best security.
At this time there is no ASP.NET tool for creating hashed passwords for insertion into configuration files. However, there are classes and methods that make it easy for you to create them programmatically. One class that can be helpful for programming this task is the FormsAuthentication class. Its HashPasswordForStoringInConfigFile method can do the hashing. At a lower level, you can use the System.Security.Cryptography classes, as well.
Forms Authentication Utilities A helper class called FormsAuthentication provides the static helper methods for managing forms authentication tickets listed in the following table.
Method
Description
Authenticate
Attempts to validate the credentials from the configured credential store, given the supplied credentials.
Decrypt
Returns an instance of a FormsAuthenticationTicket class, given an encrypted authentication ticket obtained from an HTTP form.
Encrypt
Produces a string containing an encrypted authentication ticket suitable for use in an HTTP form, given a FormsAuthenticationTicket.
GetAuthCookie
Retrieves the already encrypted authentication cookie as an HttpCookie instance. It does not add it to the Response forms collection.
GetRedirectUrl
Gets the originally requested URL, if available. For example, this method can be used to do manual redirection.
HashPasswordForStoringInConfigFile
Returns the appropriate value for storing in the Config file, given a password and the encryption type SHA1 or MD5.
Initialize
Initializes authentication forms authentication tickets.
RedirectFromLoginPage
Redirects an authenticated user back to the originally requested URL.
RenewTicketIfOld
Renews the already encrypted authentication FormsAuthenticationTicket. Returns the renewed ticket.
SetAuthCookie
Retrieves the already encrypted authentication cookie as an HttpCookie instance and adds it to the Response forms collection.
SignOut
Retrieves the already encrypted authentication form as an HttpForms instance and adds it to the outgoing response.
You can use the helper methods to customize the way the module works. You can also use them in the logon page handler to avoid the work of generating the redirection. A logon page using these facilities can be as simple as the following example:
<html>
<head>
<script language = "C#" runat=server>
void SubmitBtn_Click ( Object Source, EventArgs E ) {
// pull credentials from form fields and try to authenticate.
if ( FormsAuthentication.Authenticate ( UserName.Value, UserPassword.Value ) ) {
FormsAuthenticationTicket ticket = new
FormsAuthenticationTicket ( UserName.Value, false, 5000 );
FormsAuthentication.RedirectFromLoginPage ( UserName.Value,
PersistForms.Checked );
}
}
</script>
</head>
<body>
<form method=post runat=server>
<table>
<tr>
<td>Name:</td>
<td><input type = "text" id = "UserName" runat=server/>
</tr>
<tr>
<td>Password:</td>
<td><input type = "password" id = "UserPassword" runat=server/>
</td>
</table>
<input id = "PersistForms" runat=server />Use persistent cookie
<br>
<input type = "submit" onServerClick = "SubmitBtn_Click" runat=server />
</form>
</body>
</html>
<html>
<head>
<script language = "VB" runat=server>
Sub SubmitBtn_Click ( Source As Object, E As EventArgs )
' pull credentials from form fields and try to authenticate.
If FormsAuthentication.Authenticate ( UserName.Value, UserPassword.Value ) Then
Dim ticket As New FormsAuthenticationTicket ( _
UserName.Value, false, 5000 )
FormsAuthentication.RedirectFromLoginPage _
( UserName.Value, PersistForms.Checked )
End If
End Sub
</script>
</head>
<body>
<form method=post runat=server>
<table>
<tr>
<td>Name:</td>
<td><input type = "text" id = "UserName" runat=server/>
</tr>
<tr>
<td>Password:</td>
<td><input type = "password" id = "UserPassword" runat=server/>
</td>
</table>
<input id = "PersistForms" runat=server />Use persistent cookie
<br>
<input type = "submit" onServerClick = "SubmitBtn_Click" runat=server />
</form>
</body>
</html>
Applications that need granular control over the HTTP form properties can use the encryption helpers to encrypt the authentication ticket, but can construct the ticket and perform the redirection themselves.
Handling FormsAuthentication Events You can choose to handle the FormsAuthentication_OnAuthenticate event in order to do all forms management in whatever way you want. Although in many applications you might want to take advantage of the framework support to manage this for you, some applications might have specific requirements, such as storing credentials in the forms. These applications should handle the FormsAuthentication_OnAuthenticate event to perform forms management in whatever way desired.
The FormsAuthenticationModule exposes forms-based authentication services to ASP.NET applications. The module allows you to optionally handle a FormsAuthentication_OnAuthentication event during the authentication process.
You must provide a logon URL that collects and authenticates credentials. If the credentials are valid, you can rely upon the provided helper utilities to redirect the request to the originally requested resource with an appropriate authentication ticket. Alternatively, you can simply get the form or set it, if you do not want the redirection. For more information about authentication tickets, see Creating a Forms Authentication Ticket.
In the simplest case, you can just configure a logon URL to redirect unauthenticated requests to a page, supply a minimal implementation of that file customized from an example page, and supply valid credential pairs, either in the Web.config file or in a separate file. The framework takes care of the rest. The following example code shows how this might be handled in an ASP.NET configuration [ Web.config ] file:
<authentication mode = "forms">
<forms forms = "401kApp"
loginurl = "/login.aspx"
decryptionkey = "1!#$$*13^">
<credentials passwordFormat=SHA1>
<user name = "Mary" password = "9611E4F94EC4972D5A537EA28C69F89AD28E5B36" />
<user name = "John" password = "BA7157A99DFE9DD70A94D89844A4B4993B10168F" />
</credentials>
</forms>
</authentication>
The FormsAuthenticationModule is configured by the <forms> element in a configuration file. The following table describes how to set the forms, decryptionkey, and loginurl attributes of the <forms> element
Attribute
Description
Forms
Name of the HTTP forms to use for the authentication ticket. By default, this value is .aspxauth.
Decryptionkey
Key used to decrypt authentication tickets. Note that the default is autogenerate, so a computer-specific key is used, and the form cannot be shared between servers. This key is stored in clear text.
Loginurl
URL to which the request is redirected if it does not contain a valid authentication ticket. This should be an SSL URL ( https:// ) to prevent credentials from being posted in clear text. However, it need not be SSL-protected if the logon form itself posts back to an SSL-protected resource.
Forms Authentication Control Flow The flow of control for a forms authentication conversation is shown in the following.
1. Client requests a protected resource from a server.
GET /default.aspx
Server redirects the request to a logon page to collect credentials if there is no authentication form. Information about the originating page is placed in the query string using RETURNURL as the key.
302 Found
Location: https://samples.microsoft.com/login.aspx?RETURNURL=/default.aspx
2. Client follows the redirection to the logon page.
GET /login.aspx?RETURNURL=/default.aspx
Server returns the logon page. ( Use SSL to protect the user's credentials from being sent in clear text, at least for the post back to the logon page. )
200 OK
3. User enters credentials into the logon form.
POST /login.aspx?RETURNURL=/default.aspx
Server validates user credentials and, if the credentials are authenticated, redirects the browser to the original URL retrieved from the logon ticket. The authentication ticket is issued as a cookie.
302 Found
Location: /default.aspx
4. Follows the redirection and requests the original resource again.
GET /default.aspx
Server grants access if the user is authorized and grants the authentication form, which contains an authentication ticket. Future requests by the same browser session will be authenticated when the module inspects the form. It is possible to create a durable form that can be used for future sessions, but only until the form's expiration date.
200 OK
Set-Cookie: ASPXTICKET=ABCDEFG12345; Path=/
Creating a Forms Authentication Ticket The authentication ticket is a linear representation of the FormsAuthenticationTicket class suitable for encoding as an HTTP form or query string.
To create an authentication ticket form from a FormsAuthenticationTicket class
- Convert FormsAuthenticationTicket.IssueDate to a time_t value ( seconds since the epoch ).
- Concatenate the fields in the order in which they are represented in the class ( Version, Name, Expiration, IssueDate, IsPersistent, Expired, UserData ).
- Compute the Message Authorization Code ( MAC ) by hashing the concatenation of the previous values and the site-configured encryption key, and concatenate the MAC to the end of the data.
- Encrypt the concatenated result using a configurable, site-specific key. Use either Data Encryption Standard ( DES ) or TripleDES, depending on computer capabilities.
- Using Base64, encode the concatenated result to produce the form's value.
Forms Authentication Credentials You can allow the FormsAuthenticationModule to handle the authentication process from an application configuration file. Valid user/password pairs can be placed in the <credentials> section of a configuration file. You can compare the credentials collected from the user requesting logon privileges to the list of user/password pairs in the <credentials> section to determine if access should be granted. In the following example, users Mary and John can log on if they provide the correct password:
<credentials passwordFormat = "SHA1" >
<user name = "Mary" password = "9611E4F94EC4972D5A537EA28C69F89AD28E5B36" />
<user name = "John" password = "BA7157A99DFE9DD70A94D89844A4B4993B10168F" />
</credentials>
Notice that the credential pairs must be contained within a <credentials> section, the password format is Secure Hash Algorithm-1 ( SHA1 ), the user names are in clear text, and the passwords are hashed using the SHA1 algorithm.
The passwordFormat attribute is required, and can be one of the values listed in the following table.
Value
Description
Clear
Passwords are stored in clear text. The user password is compared directly to this value without further transformation.
MD5
Passwords are stored using a Message Digest 5 ( MD5 ) hash digest. When credentials are validated, the user password is hashed using the MD5 algorithm and compared for equality with this value. The clear-text password is never stored or compared when using this value. This algorithm produces better performance than SHA1.
SHA1
Passwords are stored using the SHA1 hash digest. When credentials are validated, the user password is hashed using the SHA1 algorithm and compared for equality with this value. The clear-text password is never stored or compared when using this value. Use this algorithm for best security.
At this time there is no ASP.NET tool for creating hashed passwords for insertion into configuration files. However, there are classes and methods that make it easy for you to create them programmatically. One class that can be helpful for programming this task is the FormsAuthentication class. Its HashPasswordForStoringInConfigFile method can do the hashing. At a lower level, you can use the System.Security.Cryptography classes, as well.
Forms Authentication Utilities A helper class called FormsAuthentication provides the static helper methods for managing forms authentication tickets listed in the following table.
Method
Description
Authenticate
Attempts to validate the credentials from the configured credential store, given the supplied credentials.
Decrypt
Returns an instance of a FormsAuthenticationTicket class, given an encrypted authentication ticket obtained from an HTTP form.
Encrypt
Produces a string containing an encrypted authentication ticket suitable for use in an HTTP form, given a FormsAuthenticationTicket.
GetAuthCookie
Retrieves the already encrypted authentication cookie as an HttpCookie instance. It does not add it to the Response forms collection.
GetRedirectUrl
Gets the originally requested URL, if available. For example, this method can be used to do manual redirection.
HashPasswordForStoringInConfigFile
Returns the appropriate value for storing in the Config file, given a password and the encryption type SHA1 or MD5.
Initialize
Initializes authentication forms authentication tickets.
RedirectFromLoginPage
Redirects an authenticated user back to the originally requested URL.
RenewTicketIfOld
Renews the already encrypted authentication FormsAuthenticationTicket. Returns the renewed ticket.
SetAuthCookie
Retrieves the already encrypted authentication cookie as an HttpCookie instance and adds it to the Response forms collection.
SignOut
Retrieves the already encrypted authentication form as an HttpForms instance and adds it to the outgoing response.
You can use the helper methods to customize the way the module works. You can also use them in the logon page handler to avoid the work of generating the redirection. A logon page using these facilities can be as simple as the following example:
<html>
<head>
<script language = "C#" runat=server>
void SubmitBtn_Click ( Object Source, EventArgs E ) {
// pull credentials from form fields and try to authenticate.
if ( FormsAuthentication.Authenticate ( UserName.Value, UserPassword.Value ) ) {
FormsAuthenticationTicket ticket = new
FormsAuthenticationTicket ( UserName.Value, false, 5000 );
FormsAuthentication.RedirectFromLoginPage ( UserName.Value,
PersistForms.Checked );
}
}
</script>
</head>
<body>
<form method=post runat=server>
<table>
<tr>
<td>Name:</td>
<td><input type = "text" id = "UserName" runat=server/>
</tr>
<tr>
<td>Password:</td>
<td><input type = "password" id = "UserPassword" runat=server/>
</td>
</table>
<input id = "PersistForms" runat=server />Use persistent cookie
<br>
<input type = "submit" onServerClick = "SubmitBtn_Click" runat=server />
</form>
</body>
</html>
<html>
<head>
<script language = "VB" runat=server>
Sub SubmitBtn_Click ( Source As Object, E As EventArgs )
' pull credentials from form fields and try to authenticate.
If FormsAuthentication.Authenticate ( UserName.Value, UserPassword.Value ) Then
Dim ticket As New FormsAuthenticationTicket ( _
UserName.Value, false, 5000 )
FormsAuthentication.RedirectFromLoginPage _
( UserName.Value, PersistForms.Checked )
End If
End Sub
</script>
</head>
<body>
<form method=post runat=server>
<table>
<tr>
<td>Name:</td>
<td><input type = "text" id = "UserName" runat=server/>
</tr>
<tr>
<td>Password:</td>
<td><input type = "password" id = "UserPassword" runat=server/>
</td>
</table>
<input id = "PersistForms" runat=server />Use persistent cookie
<br>
<input type = "submit" onServerClick = "SubmitBtn_Click" runat=server />
</form>
</body>
</html>
Applications that need granular control over the HTTP form properties can use the encryption helpers to encrypt the authentication ticket, but can construct the ticket and perform the redirection themselves.
Handling FormsAuthentication Events You can choose to handle the FormsAuthentication_OnAuthenticate event in order to do all forms management in whatever way you want. Although in many applications you might want to take advantage of the framework support to manage this for you, some applications might have specific requirements, such as storing credentials in the forms. These applications should handle the FormsAuthentication_OnAuthenticate event to perform forms management in whatever way desired.
Dictionary
English Dictionary
Double click on any word on the page or type a word:
Powered by DictionaryBox.com