asp.net forms authentication and authori

Forms Authentication

Forms authentication works on the principal of authentication tickets (created when user logs on).
This authentication ticket is normally contained in a cookie but can also reside in a query string.
Make use of the membership provider to authenticate users.

The class responsible for handling Forms authentication is called FormsAuthenticationModule.
This is an HTTP module that participates in the regular ASP.NET page-processing cycle.

Authentication is specified by the authentication's mode attribute (forms / windows / passport / none)

Configuration (web.config)

The attributes are as follows:

  • loginUrl points to your application's custom logon page. (Remember to put this page in a folder that requires SSL if possible to ensure the integrity of the credentials when passed from the browser to server)
  • protection (all, encryption, none, validation) specify privacy and integrity for the forms authentication ticket. (Encryption uses the algorithm specified on the machineKey element)
  • timeout is used to specify a limited lifetime for the forms authentication session. By default 30 minutes (This also works with a persistent forms authentication cookie)
  • name and path are set to the values defined in the application's configuration file.
  • requireSSL set to (true or false)
  • slidingExpiration is set to true to enforce a sliding session lifetime. This means that the session timeout is periodically reset as long as a user stays active on the site.
  • defaultUrl is set as first page for successful login.
  • cookieless specifies if the application use cookies for all browsers that support cookies.
  • enableCrossAppRedirects when set to false it indicates that forms authentication does not support automatic processing of tickets that are passed between applications on the query string or as part of a form POST.


The UrlAuthorizationModule class is used to ensure that only authenticated users can access a certain page.

This is done by configuring the authorization element.

e.g.  <deny users="?" />

This setting will deny all unauthenticated users to access any page in your application. 

if (Membership.ValidateUser(userName.Text, password.Text))
{    if (Request.QueryString["ReturnUrl"] != null)   
{        FormsAuthentication.RedirectFromLoginPage(userName.Text, false);    }    else    {        FormsAuthentication.SetAuthCookie(userName.Text, false);    }}else{    Response.Write("Invalid UserID and Password");}  


ASP.NET 2.0 defines a set of HTTP modules in the machine-level Web.config file. These include a number of authentication modules as shown here:  <httpModules>  …  <add name="WindowsAuthentication"       type="System.Web.Security.WindowsAuthenticationModule" />  <add name="FormsAuthentication"        type="System.Web.Security.FormsAuthenticationModule" />  <add name="PassportAuthentication"        type="System.Web.Security.PassportAuthenticationModule" />  …</httpModules>  

Forms Authentication Cookies

The FormsAuthentication class creates the authentication cookie automatically when the FormsAuthentication.SetAuthCookie or FormsAuthentication.RedirectFromLoginPage methods are called.

The following properties are included in a typical forms authentication cookie:

  • Name. This property specifies the name of the cookie.
  • Value. This property specifies value of the cookie.

In a typical forms authentication cookie, the value contains a string representation of the encrypted and signed FormsAuthenticationTicket object. The cookie contains the following properties:

  • Expires. This property specifies the expiration date and time for the cookie. Forms authentication only sets this value if your code indicates that a persistent forms-authentication cookie should be issued.
  • Domain. This property specifies the domain with which the cookie is associated. The default value is null.
    • HasKeys. This property indicates whether the cookie has subkeys.
  • HttpOnly. This property specifies whether the cookie can be accessed by client script. In ASP.NET 2.0, this value is always set to true. Internet Explorer 6 Service Pack 1 supports this cookie attribute, which prevents client-side script from accessing the cookie from the document.cookie property. If an attempt is made to access the cookie from client-side script, an empty string is returned. The cookie is still sent to the server whenever the user browses to a Web site in the current domain.

    Note   Web browsers that do not support the HttpOnly cookie attribute either ignore the cookie or ignore the attribute, which means that the session is still subject to cross-site scripting attacks.

  • Path. This property specifies the virtual path for the cookie. The default value is "/", indicating root directory.
  • Secure. This property specifies whether the cookie should only be transmitted over an HTTPS connection. The Secure property should be set to true so that the cookie is protected by SSL encryption.
  • Version. This property specifies the version number of the cookie.

Creating the Forms Authentication Cookie

The forms authentication cookie is created by the FormsAuthentication class as follows. Once the user is validated, the FormsAuthentication class internally creates a FormsAuthenticationTicket object by specifying the cookie name; the version of the cookie; the directory path; the issue date of the cookie; the expiration date of the cookie; whether the cookie should be persisted; and, optionally, user-defined data.

									FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,        "userName",        DateTime.Now,        DateTime.Now.AddMinutes(30), // value of time out property        false, // Value of IsPersistent property        String.Empty,        FormsAuthentication.FormsCookiePath);  						

Next, forms authentication uses the Encrypt method for encrypting and signing the forms authentication ticket, if the protection attribute of the forms element is set to All or Encryption.

									string encryptedTicket = FormsAuthentication.Encrypt(ticket);  						

The following text shows the process used when the protection attribute is set to All:

  • Create a serialized forms authentication ticket. A byte array representation of the ticket is created.
  • Sign the forms authentication ticket. The message authentication code (MAC) value for the byte array is computed by using the algorithm and key specified by the validation and validationKey attributes of the machineKey element. By default, the SHA1 algorithm is used.
  • Encrypt forms authentication ticket. The second byte array that has been created is encrypted by using the Encrypt method of the FormsAuthentication class. The Encrypt method internally uses the algorithm and key specified by the decryption and decryptionKey attributes on the machineKey element. ASP.NET version 1.1 uses the 3DES algorithm by default. ASP.NET version 2.0 uses the Rinjdael (AES) algorithm by default.
  • Create HTTP cookie or query string as appropriate. The encrypted authentication ticket is then added to an HttpCookie object or query string if forms authentication is configured for cookieless authentication. The cookie object is created using the following code:
    												HttpCookie authCookie = new HttpCookie(                            FormsAuthentication.FormsCookieName,                             encryptedTicket);  								
  • Set forms authentication cookie as secure. If the forms authentication ticket is configured to use SSL, the HttpCookie. Secure property is set to true. This instructs browsers to only send the cookie over HTTPS connections.
    												authCookie.Secure = true;  								
  • Set the HttpOnly bit. In ASP.NET 2.0, this bit is always set.
  • Set appropriate cookie attributes. If needed, set the path, domain and expires attributes of the cookie.
  • Add the cookie to the cookie collection. The authentication cookie is added to the cookie collection to be returned to the client browser.

Each time a subsequent request is received after authentication, the FormsAuthenticationModule class retrieves the authentication ticket from the authentication cookie, decrypts it, computes the hash value, and compares the MAC value to help ensure that the cookie has not been tampered with. Finally, the expiration time contained inside of the forms authentication ticket is verified.

Note   ASP.NET does not depend on the expiration date of the cookie because this date could be easily forged.

Role Authorization

In ASP.NET 2.0, role authorization has been simplified. You no longer need to retrieve role information when the user is authenticated or add role details to the authentication cookie. The .NET Framework 2.0 includes a role management API that enables you to create and delete roles, and add users to and remove users from roles. The role management API stores its data in an underlying data store that it accesses through an appropriate role provider for that data store. The following role providers are included with the .NET Framework 2.0 and can be used with forms authentication:

  • SQL Server. This is the default provider and it stores role information in a SQL Server database.
  • Authorization Manager (AzMan). This provider uses an AzMan policy store in an XML file, in Active Directory, or in Active Directory Application Mode (ADAM) as its role store. It is typically used in an intranet or extranet scenario where Windows authentication and Active Directory are used for authentication.

For more information about using the role management API, see How To: Use Role Manager in ASP.NET 2.0.

Cookieless Forms Authentication

ASP.NET 2.0 supports cookieless forms authentication. This feature is controlled by the cookieless attribute of the forms element. This attribute can be set to one of the following four values:

  • UseCookies. This value forces the FormsAuthenticationModule class to use cookies for transmitting the authentication ticket.
  • UseUri. This value directs the FormsAuthenticationModule class to rewrite the URL for transmitting the authentication ticket.
  • UseDeviceProfile. This value directs the FormsAuthenticationModule class to look at the browser capabilities. If the browser supports cookies, then cookies are used; otherwise, the URL is rewritten.
  • AutoDetect. This value directs the FormsAuthenticationModule class to detect whether the browser supports cookies through a dynamic detection mechanism. If the detection logic indicates that cookies are not supported, then the URL is rewritten.

If your application is configured to use cookieless forms authentication and the FormsAuthentication.RedirectFromLoginPage method is being used, then the FormsAuthenticationModule class automatically sets the forms authentication ticket in the URL. The following code example shows what a typical URL looks like after it has been rewritten:



The section of the URL that is in parentheses contains the data that the cookie would usually contain. This data is removed by ASP.NET during request processing. This step is performed by the ASP.NET ISAPI filter and not in an HttpModule class. If you read the Request.Path property from an .aspx page, you won't see any of the extra information in the URL. If you redirect the request, the URL will be rewritten automatically.

Note   It is not possible to secure authentication tickets contained in URLs. When security is paramount, you should use cookies to store authentication tickets.

Membership and Login Controls

ASP.NET 2.0 introduces a membership feature and set of login Web server controls that simplify the implementation of applications that use forms authentication.

Membership provides credential storage and management for application users. It also provides a membership API that simplifies the task of validating user credentials when used with forms authentication. The membership feature is built on top of a provider model. This model allows implementing and configuring different providers pointing to different user stores. ASP.NET 2.0 includes the following membership providers:

  • Active Directory membership provider. This provider uses either an Active Directory or Active Directory Application Mode (ADAM) user store.
  • SQL Server membership provider. This provider uses a SQL Server user store.

You can also add support for custom user stores. For example, you can add support for other Lightweight Directory Access Protocol (LDAP) directories or other existing corporate identity stores. To do so, create a custom provider that inherits from the MembershipProvider abstract base class.

ASP.NET login controls automatically use membership and forms authentication and encapsulate the logic required to prompt users for credentials, validate users, recover or replace passwords, and so on. In effect, the ASP.NET login controls provide a layer of abstraction over forms authentication and membership, and they replace most, or all of, the work you would normally have to do to use forms authentication.

For more information about using the membership feature and login controls, see How To: Use Membership in ASP.NET 2.0.

Web Farm Scenarios

In a Web farm, you cannot guarantee which server will handle successive requests. If a user is authenticated on one server and the next request goes to another server, the authentication ticket will fail the validation and require the user to re-authenticate.

The validationKey and decryptionKey attributes in the machineKey element are used for hashing and encryption of the forms authentication ticket. The default value for these attributes is AutoGenerate.IsolateApps. The keys are auto-generated for each application, and they are different on each server. Therefore, authentication tickets that are encrypted on one computer cannot be decrypted and verified on another computer in a Web farm, or in another application on the same Web server.

To address this issue, the validationKey and decryptionKey values must be identical on all computers in the Web farm. For more information about configuring the machineKey element, see How To: Configure MachineKey in ASP.NET 2.0.

What's your thoughts on this?


Protected by WP Anti Spam