Explained: Forms Authentication in ASP.NET 2.0

 

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

patterns & practices Developer Center

patterns & practices Developer Center

J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Chaitanya Bijwe

Microsoft Corporation

November 2005

Applies To

ASP.NET version 2.0

Summary

This module explains how forms authentication works in ASP.NET version 2.0. It explains how IIS and ASP.NET authentication work together, and it explains the role and operation of the FormsAuthenticationModule class.

Contents

Objectives
Overview
IIS Authentication
ASP.NET Forms Authentication
Cookieless Forms Authentication
Membership and Login Controls
Web Farm Scenarios
Additional Resources

Objectives

  • Learn how forms authentication works in ASP.NET version 2.0.
  • Understand how forms authentication configuration affects the generation of the forms authentication ticket.
  • See what's stored in a forms authentication ticket.
  • Learn how cookieless forms authentication works.
  • Identify Web farm considerations for forms authentication.

Overview

Forms authentication uses an authentication ticket that is created when a user logs on to a site, and then it tracks the user throughout the site. The forms authentication ticket is usually contained inside a cookie. However, ASP.NET version 2.0 supports cookieless forms authentication, which results in the ticket being passed in a query string.

If the user requests a page that requires authenticated access and that user has not previously logged on to the site, then the user is redirected to a configured logon page. The logon page prompts the user to supply credentials, typically a user name and password. These credentials are then passed to the server and validated against a user store, such as a SQL Server database. In ASP.NET 2.0, user-store access can be handled by a membership provider. After the user's credentials are authenticated, the user is redirected to the originally requested page.

Forms authentication processing is handled by the FormsAuthenticationModule class, which is an HTTP module that participates in the regular ASP.NET page-processing cycle. This document explains how forms authentication works in ASP.NET 2.0.

IIS Authentication

ASP.NET authentication is a two-step process. First, Internet Information Services (IIS) authenticates the user and creates a Windows token to represent the user. IIS determines the authentication mode that it should use for a particular application by looking at IIS metabase settings. If IIS is configured to use anonymous authentication, a token for the IUSR_MACHINE account is generated and used to represent the anonymous user. IIS-then passes the token to ASP.NET.

Second, ASP.NET performs its own authentication. The authentication method used is specified by the mode attribute of the authentication element. The following authentication configuration specifies that ASP.NET uses the FormsAuthenticationModule class:

<authentication mode="Forms" />
  

Note   Because forms authentication does not rely on IIS authentication, you should configure anonymous access for your application in IIS if you intend to use forms authentication in your ASP.NET application.

ASP.NET Forms Authentication

ASP.NET forms authentication occurs after IIS authentication is completed. You can configure forms authentication with the forms element.

Forms Authentication Configuration

The default attribute values for forms authentication are shown in the following configuration-file fragment.

<system.web>
  <authentication mode="Forms">
    <forms loginUrl="Login.aspx"
           protection="All"
           timeout="30"
           name=".ASPXAUTH" 
           path="/"
           requireSSL="false"
           slidingExpiration="true"
           defaultUrl="default.aspx"
           cookieless="UseDeviceProfile"
           enableCrossAppRedirects="false" />
  </authentication>
</system.web>
  

The default attribute values are described below:

  • loginUrl points to your application's custom logon page. You should place the logon page in a folder that requires Secure Sockets Layer (SSL). This helps ensure the integrity of the credentials when they are passed from the browser to the Web server.
  • protection is set to All to specify privacy and integrity for the forms authentication ticket. This causes the authentication ticket to be encrypted using the algorithm specified on the machineKey element, and to be signed using the hashing algorithm that is also specified on the machineKey element.
  • timeout is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.
  • name and path are set to the values defined in the application's configuration file.
  • requireSSL is set to false. This configuration means that authentication cookies can be transmitted over channels that are not SSL-encrypted. If you are concerned about session hijacking, you should consider setting requireSSL to true.
  • 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 to the Default.aspx page for the application.
  • cookieless is set to UseDeviceProfile to specify that the application use cookies for all browsers that support cookies. If a browser that does not support cookies accesses the site, then forms authentication packages the authentication ticket on the URL.
  • enableCrossAppRedirects is set to false to indicate 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.

Authorization Configuration

In IIS, anonymous access is enabled for all applications that use forms authentication. The UrlAuthorizationModule class is used to help ensure that only authenticated users can access a page.

You can configure UrlAuthorizationModule by using the authorization element as shown in the following example.

<system.web>
  <authorization>
    <deny users="?" />
  </authorization>
</system.web>
  

With this setting, all unauthenticated users are denied access to any page in your application. If an unauthenticated user tries to access a page, the forms authentication module redirects the user to the logon page specified by the loginUrl attribute of the forms element.

Forms Authentication Control Flow

Figure 1 shows the sequence of events that occur during forms authentication.

Ff647070.formsauth(en-us,PandP.10).gif

Figure 1. Forms authentication control flow

  1. The user requests the Default.aspx file from your application's virtual directory. IIS allows the request because anonymous access is enabled in the IIS metabase. ASP.NET confirms that the authorization element includes a <deny users="?" /> tag.

  2. The server looks for an authentication cookie. If it fails to find the authentication cookie, the user is redirected to the configured logon page (Login.aspx), as specified by the LoginUrl attribute of the forms element. The user supplies and submits credentials through this form. Information about the originating page is placed in the query string using RETURNURL as the key. The server HTTP reply is as follows:

    302 Found Location: 
    https://localhost/FormsAuthTest/login.aspx?RETURNURL=%2fFormAuthTest%2fDefault.aspx
    
    
  3. The browser requests the Login.aspx page and includes the RETURNURL parameter in the query string.

  4. The server returns the logon page and the 200 OK HTTP status code.

  5. The user enters credentials on the logon page and posts the page, including the RETURNURL parameter from the query string, back to the server.

  6. The server validates user credentials against a store, such as a SQL Server database or an Active Directory user store. Code in the logon page creates a cookie that contains a forms authentication ticket that is set for the session.

    In ASP.NET 2.0, the validation of user credentials can be performed by the membership system. The Membership class provides the ValidateUser method for this purpose as shown here:

    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");
    }
    
    

    Note   When using the Login Web server control, it automatically performs the following steps for you. The preceding code is provided for context.

  7. For the authenticated user, the server redirects the browser to the original URL that was specified in the query string by the RETURNURL parameter. The server HTTP reply is as follows:

    302 Found Location: 
    https://localhost/TestSample/default.aspx
    
    
  8. Following the redirection, the browser requests the Default.aspx page again. This request includes the forms authentication cookie.

  9. The FormsAuthenticationModule class detects the forms authentication cookie and authenticates the user. After successful authentication, the FormsAuthenticationModule class populates the current User property, which is exposed by the HttpContext object, with information about the authenticated user.

  10. Since the server has verified the authentication cookie, it grants access and returns the Default.aspx page.

FormsAuthenticationModule

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>
  

Only one authentication module is used for each request. The authentication module that is used depends on which authentication mode has been specified by the authentication element, usually in the Web.config file in the application's virtual directory.

The FormsAuthenticationModule class is activated when the following element is in the Web.config file.

<authentication mode="Forms" />
  

The FormsAuthenticationModule class constructs a GenericPrincipal object and stores it in the HTTP context. The GenericPrincipal object holds a reference to a FormsIdentity instance that represents the currently authenticated user. You should allow forms authentication to manage these tasks for you. If your applications have specific requirements, such as setting the User property to a custom class that implements the IPrincipal interface, your application should handle the PostAuthenticate event. The PostAuthenticate event occurs after the FormsAuthenticationModule has verified the forms authentication cookie and created the GenericPrincipal and FormsIdentity objects. Within this code, you can construct a custom IPrincipal object that wraps the FormsIdentity object, and then store it in the HttpContext. User property.

Note   If you do this, you will also need to set the IPrincipal reference on the Thread.CurrentPrincipal property to ensure that the HttpContext object and the thread point to the same authentication information.

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.

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 theHttpOnly 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.

    Response.Cookies.Add(authCookie);
    
    

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:

https://localhost/CookielessFormsAuthTest/(F(-k9DcsrIY4CAW81Rbju8KRnJ5o_gOQe0I1E_jNJLYm74izyOJK8GWdfoebgePJTEws0Pci7fHgTOUFTJe9jvgA2))/Test.aspx
  

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.

Additional Resources

Feedback

Provide feedback by using either a Wiki or e-mail:

We are particularly interested in feedback regarding the following:

  • Technical issues specific to recommendations
  • Usefulness and usability issues

Technical Support

Technical support for the Microsoft products and technologies referenced in this guidance is provided by Microsoft Support Services. For product support information, please visit the Microsoft Support Web site at https://support.microsoft.com.

Community and Newsgroups

Community support is provided in the forums and newsgroups:

To get the most benefit, find the newsgroup that corresponds to your technology or problem. For example, if you have a problem with ASP.NET security features, you would use the ASP.NET Security forum.

Contributors and Reviewers

  • External Contributors and Reviewers: Jason Taylor, Security Innovation; Rudolph Araujo, Foundstone Professional Services
  • Microsoft PSS Contributors and Reviewers: Tom Christian, Wade Mascia
  • Microsoft Product Group: Stefan Schackow
  • Test team: Larry Brader, Microsoft Corporation; Nadupalli Venkata Surya Sateesh, Sivanthapatham Shanmugasundaram, Infosys Technologies Ltd.
  • Edit team: Lara Ballinger, Nelly Delgado, Microsoft Corporation
  • Release Management: Sanjeev Garg, Microsoft Corporation

patterns & practices Developer Center

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.