web analytics

Understanding ASP.NET Authentication

Options

codeling 1595 - 6639
@2016-03-23 13:02:11

Authentication is the process of obtaining identification credentials such as name and password from a user and validating those credentials against some authority. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity.

Once an identity has been authenticated, the authorization process determines whether that identity has access to a given resource.

ASP.NET implements authentication through authentication providers, the code modules that contain the code necessary to authenticate the requestor's credentials. The topics in this section describe the authentication providers built into ASP.NET.

Term

Definition

Windows Authentication Provider

Provides information on how to use Windows authentication in conjunction with Microsoft Internet Information Services (IIS) authentication to secure ASP.NET applications.

Forms Authentication Provider

Provides information on how to create an application-specific login form and perform authentication using your own code. A convenient way to work with forms authentication is to use ASP.NET membership and ASP.NET login controls, which together provide a way to collect user credentials, authenticate them, and manage them, using little or no code.

@2016-03-23 13:16:24

ASP.NET Forms Authentication

Forms authentication enables you to authenticate the user name and password of your users using a login form that you create. Unauthenticated requests are redirected to a login page, where the user provides credentials and submits the form. If the application authenticates the request, the system issues a ticket (authentication token) that contains a key for reestablishing the identity for subsequent requests. You can maintain the authentication token in a cookie or in the page URL.

To use forms authentication, you create a login page that collects credentials from the user and that includes code to authenticate the credentials. Typically you configure the application by using the authentication configuration element(<authentication>) in the web.config file to redirect requests to the login page when users try to access a protected resource, such as a page that requires authentication.

@2016-03-23 13:48:30

Forms Authentication Configurations

By default, ASP.NET applications use Windows authentication. To change the authentication type to forms authentication, then, we need to modify the <authentication> element’s mode attribute to Forms. The <authentication> element will include a <forms> child element that contains forms authentication-specific settings.

<authentication mode="Forms">
<forms
    name="name"
    loginUrl="URL"
    defaultUrl="URL"
    protection="[All|None|Encryption|Validation]"
    timeout="[MM]"
    path="path"
    requireSSL="[true|false]"
    slidingExpiration="[true|false]">
    enableCrossAppRedirects="[true|false]"
    cookieless="[UseUri|UseCookies|AutoDetect|UseDeviceProfile]"
    domain="domain name"
    ticketCompatibilityMode="[Framework20|Framework40]">
    <credentials>...</credentials>
</forms>
</authentication>

The following table describe attributes:

 

Description

cookieless

Optional attribute.

Defines whether cookies are used and their behavior.

This attribute can be one of the following values.

NoteNote
In AJAX-enabled ASP.NET Web sites, use the default value UseCookies for the cookieless attribute. Settings that use cookies encoded in the URL are not supported by the ASP.NET AJAX client-script libraries.
 
ValueDescription
  • UseCookies: Specifies that cookies will always be used, regardless of the device.

  • UseUri: Specifies that cookies will never be used.

  • AutoDetect: Specifies that cookies are used, if the device profile supports cookies; otherwise, cookies are not used.For desktop browsers that are known to support cookies, a probing mechanism will be used to try to use cookies, when enabled. If a device does not support cookies, no probing mechanism will be used.

  • UseDeviceProfile: Specifies that cookies are used, if the browser supports cookies; otherwise, cookies are not used. For devices that support cookies, no attempt is made to probe to determine whether cookie support is enabled.

This attribute is new in the .NET Framework version 2.0.

The default is UseDeviceProfile.

defaultUrl

Optional attribute.

Defines the default URL that is used for redirection after authentication.

This attribute is new in the .NET Framework version 2.0.

The default is "default.aspx".

domain

Optional attribute.

Specifies an optional domain to set on outgoing forms-authentication cookies. This setting takes precedence over the domain that is used in the httpCookies element.

This attribute is new in the .NET Framework version 2.0.

The default is an empty string ("").

enableCross

AppRedirects

Optional attribute.

Indicates whether authenticated users are redirected to URLs in other Web applications.

NoteNote
When performing redirects across applications, you must make sure that several of the attributes in the forms Element for authentication (ASP.NET Settings Schema) are duplicated across the authenticated applications.

This attribute can be one of the following values.

 
ValueDescription
  • True: Specifies that authenticated users can be redirected to URLs in other Web applications.

  • False: Specifies that authenticated users cannot be redirected to URLs in other Web applications.

This attribute is new in the .NET Framework version 2.0.

The default is False.

loginUrl

Optional attribute.

Specifies the URL to which the request is redirected for logon, if no valid authentication cookie is found.

The default is login.aspx.

name

Optional attribute.

Specifies the HTTP cookie to use for authentication. This sets the suffix for the name of the cookie that contains the authentication ticket.

If multiple applications are running on a single server and each application requires a unique cookie, you must configure the cookie name in each Web.config file for each application.

The default is ".ASPXAUTH".

path

Optional attribute.

Specifies the path for cookies that are issued by the application.

The default is a slash (/), because most browsers are case-sensitive and will not send cookies back, if there is a path case mismatch.

protection

Optional attribute.

Specifies the type of encryption, if any, to use for cookies.

This attribute can be one of the following values.

 
ValueDescription
  • All: Specifies that the application uses both data validation and encryption to help protect the cookie. This option uses the configured data validation algorithm, which is based on the machineKey element. Triple-DES (3DES) is used for encryption, if it is available and if the key is long enough (48 bytes or more). All is the default, and recommended, value.

  • Encryption: Specifies that the cookie is encrypted by using 3DES or DES, but data validation is not performed on the cookie. Cookies used in this manner might be subject to chosen plain-text attacks.

  • None: Specifies that both encryption and validation are disabled for sites that are using cookies only for personalization and have less stringent security requirements. You should not use cookies in this manner; however, it is the least resource-intensive way to enable personalization in the .NET Framework.

  • Validation: Specifies that a validation scheme verifies that the contents of an encrypted cookie have not been changed in transit. The cookie is created by using cookie validation by concatenating a validation key with the cookie data, computing a message authentication code (MAC), and appending the MAC to the outgoing cookie.

The default is All.

requireSSL

Optional attribute.

Specifies whether an SSL connection is required to transmit the authentication cookie.

This attribute can be one of the following values.

 
ValueDescription
  • True: Specifies that an SSL connection is required to help protect the user's credentials. If True, ASP.NET sets the Secure property for the authentication cookie and a compliant browser does not return the cookie, unless the connection is using SSL.

  • False: Specifies that an SSL connection is not required to transmit the cookie. The default is False.

The default is False.

slidingExpiration

Optional attribute.

Specifies whether sliding expiration is enabled. Sliding expiration resets the active authentication time for a cookie to expire upon each request during a single session.

This attribute can be one of the following values.

 
ValueDescription
  • True: Specifies that sliding expiration is enabled. The authentication cookie is refreshed and the time to expiration is reset on subsequent requests during a single session.

  • False: Specifies that sliding expiration is not enabled and the cookie expires at a set interval from the time the cookie was originally issued.

The default is True.

ticketCompatibilityMode

Optional attribute.

Specifies whether to use Coordinated Universal Time (UTC) or local time for the ticket expiration date for forms authentication.

This attribute can HAVE one of the following values.

 
ValueDescription
  • Framework20: Specifies that the ticket expiration date is stored using local time.

  • Framework40: Specifies that the ticket expiration date is stored using UTC.

The default value is Framework20.

timeout

Optional attribute.

Specifies the time, in integer minutes, after which the cookie expires. If the SlidingExpiration attribute is true, the timeout attribute is a sliding value, expiring at the specified number of minutes after the time that the last request was received. To prevent compromised performance, and to avoid multiple browser warnings for users who have cookie warnings turned on, the cookie is updated when more than half of the specified time has elapsed. This might cause a loss of precision.

The default is "30" (30 minutes).

@2016-12-13 23:32:59

Forms Authentication Control Flow

The flow of control for ASP.NET forms authentication is shown in the following table.

 

Browser and HTTP operation

Server reply

Requests a protected resource from a server. The HTTP operation is:

GET /default.aspx

If there is no authentication cookie, redirects the request to a logon page to collect credentials. Information about the originating page is placed in the query string using RETURNURL as the key. The server HTTP reply is:

Follows the redirection to the logon page. The HTTP operation is:

GET /logon.aspx?RETURNURL=/default.aspx

Returns the logon page. For security, we recommend that you use Secure Sockets Layer (SSL) for the logon page to keep the user's credentials from being sent in clear text. The server HTTP reply is:

200 OK

After user enters credentials into the logon page, submits the page. The HTTP operation is:

POST /logon.aspx?RETURNURL=/default.aspx

Validates user credentials and, if the credentials are authenticated, redirects the browser to the original URL specified in the QueryString as the RETURNURL variable. By default, the authentication ticket is issued as a cookie.

Note Note

You can specify that the authentication ticket be included in the URL instead of a cookie using the CookieMode property.

The server HTTP reply is:

302 Found
Location: /default.aspx

Follows the redirection and requests the original resource again. The HTTP operation is:

GET /default.aspx

If the user is authenticated, grants access and grants the authentication cookie, which contains an authentication ticket. Future requests by the same browser session will be authenticated when the FormsAuthenticationModule module inspects the cookie. It is possible to create a persistent cookie that can be used for future sessions, but only until the cookie's expiration date. The server HTTP reply is:

200 OK
Set-Cookie: ASPXTICKET=ABCDEFG12345;Path=/

Note that the cookie path is set to /. Because cookie names are case-sensitive, this prevents inconsistent case in URLs on the site. For example, if the path were set to /SavingsPlan and a link contained /savingsplan, the user would be forced to re-authenticate because the browser would not send the cookie.

The following figure and steps shows the sequence of events that occur during forms authentication.

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

 

  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: 
    http://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, 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))
    {
        //Maintain the authentication token in a cookie
        if (Request.QueryString["ReturnUrl"] != null)
        {
            FormsAuthentication.RedirectFromLoginPage(userName.Text, false);
        }
        else
        {
            FormsAuthentication.SetAuthCookie(userName.Text, false);
        }
    }
    else
    {
        Response.Write("Invalid UserID and Password");
    }
    
  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: 
    http://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.

 

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com