ASP. NET form authentication details)

Source: Internet
Author: User
Tags account security

This section describes how to perform form authentication in ASP. NET 2.0 and how IIS and ASP. net2.0 form authentication mechanisms are combined.

Summary

When a user successfully logs on to the website using the user name, formsauthentication creates an authentication ticket (authentication ticket ), with this ticket, you can track the user throughout the website. Form authentication ticket is usually contained in a cookie, but ASP. net2.0 also supports formsauthentication without Cookie. At this time, ticket needs to be passed through query string.

When a user logs on to a website, authentication is required to access the website. If he has not entered the authentication information (usually the user name and password), the user will be redirected to a login page. On the login page, you can enter verification information, which is then sent to the server to compare the information with a media (such as SQL Server or a file) that stores user identity information. In ASP. net2.0, you can use membership proivder to access information stored in sqlserver. (The provider mode has many advantages and will be described in detail later .) After the user information is verified, the user is allowed to access the desired page.

Formsauthentication is executed through the formsauthenticationmodule class, which is part of the runtime of the Asp.net page. The following explains how formsauthentication works in ASP. net2.0.

IIS Verification

Asp.net authentication is divided into two steps. First, IIS verifies that the current user has the permission to access the website using the Windows account. If IIS access is configured as anonymous, any user can access the page.

Then, after IIS verification is complete, Asp.net starts to perform its own verification. The authentication mode can be configured in the web. config file. If you write <Authentication mode = "forms"/> In the config file, Asp.net will know that the formsauthenticationmodule class is used for verification.

ASP. NET froms Authentication

Froms authentication configuration: You can configure it in the config file. The configuration is as follows:

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

These attributes are described as follows:

Loginurl: points to the login page. You should place the login page in a folder that requires Secure Sockets Layer (SSL. In this way, account security and integrity can be guaranteed.

Potection: "All" indicates that authentication ticket is encrypted. the encryption algorithm is defined in the machinekey element and is signed by the hash algorithm. This algorithm is also defined in the machinekey.

Timout: This attribute defines the expiration time of the verification session. The default value is 30 minutes.

Requiressl: This attribute is set to false, which indicates that the verified cookies can be transmitted over SSL encrypted transmission. If you pay special attention to session security, you need to set it to true.

Slidingexpiration: This attribute is set to true, which indicates that the session will not expire as long as the user continues to maintain activity on the website.

Defaulturl: This attribute indicates the default page after login.

Cookieless: This attribute is set to usedeviceprofile, which indicates that the cookie will be used in any browser that supports it. If the browser does not support cookies, form authentication will pass authentication ticket through URL.

Enablecrossappredirects: Indicates whether authenticated users can be redirected to other web applications. True indicates yes, and false indicates no.

Authorization configuration (user configuration)

Urlauthorizationmodule is used to ensure that only authenticated users can access the page. You can configure the class in the web. config file as follows:
<System. Web>

<Authorization>

<Deny users = "? "/>

</Authorization>

</System. Web>

The preceding configuration indicates that all users who fail the verification will be denied access to the page. If an unauthenticated user attempts to access the page, the user will be redirected to the login page defined by the loginurl attribute.

Forms authentication control process

For the process of Forms authentication, refer:

Let's analyze the above process:

Step 1: When you access the default. aspx page, IIS is verified and ASP. NET discovers authorization.

The element contains <deny users = "? "/> Label.

Step 2: The server looks for a cookie that contains authentication information. If this cookie is not found, the user will be redirected to the login page. Is the page specified by loginurl. The user will enter the login information on that page. :

Step 3: the browser requests to browse the logon page and pass the returnurl parameter value.

Step 4: transfer the server to the login page.

Step 5: The user enters the authentication information and submits data, which also contains the returnurl parameter value.

Part 6: The server verifies user information by reading storage media (such as the sqserver database. On the login page, create a cookie containing form authentication ticket as the session.

In ASP. net2.0, you can use the membership system for authentication. The membership class provides the validateuser method. For details, refer:

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

}

Step 7: The user authentication is successful, and the server re-directs the browser to the page specified by retururl.

Step 8: at the same time of redirection, the browser sends a request to the default. aspx page, which contains the user's forms authentication cookie.

Step 9: The formsauthenticationmodule class detects the forms authentication cookie and starts verification. After the verification is successful, the class obtains the current user information and sends it to the httpcontext object. You can use the httpcontext object to obtain information about the current user.

Step 1: The verification is successful!

Formsauthenticationmodule

ASP. NET 2.0 defines a series of HTTP modules in the system's default web. config file, including a series of verification modules as follows:

<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"/>...

You can use only one authentication module for each request. The verification mode is usually defined in the web. config file:

<Authentication mode = "forms"/> indicates that formsauthentication is used.

The formsauthenticationmodule class creates a genericprincipal object and stores it in the HTTP context. Genericprincipal contains a reference of a formsidentity instance, and a formsidentity instance contains user information. Generally, you will use forms authentication to complete the above work for you. However, if your program has other special requirements, such as passing user information to a custom class (which inherits the iprincipal Interface), your program needs to write code in the postauthenticate event. The postauthenticate event is triggered after formsauthenticationmodule verifies Forms authentication cookie and creates genericprincipal and formsidentity objects. After this event is triggered, you can create a custom iprincipal object in the event, use this object to encapsulate the formsidentity object, and then save the custom iprincipal object to httpcontext.

Note: If you want to customize an ipricipal object, you must set reference for the custom object in the current thread: for example: thread. currentprincipal = newgenericprincipal (New genericidentity ("Bob", "Passport"), rolesarray );

In this way, the httpcontext object and thread point to the information of the same authenticated user.

Forms authentication cookies

The formsauthentication class automatically creates a verification cookie after the formsauthentication. setauthcookie or formsauthentication. redirectfromloginpage method is called;

A typical authentication cookie contains the following two attributes:

Name: Cookie name

Value: the cookie value.

In a typical forms authentication cookie, the cookie value is encrypted and a formauthenticationticket signature is created. Cookies contain the following attributes:

Expires: This attribute indicates the cookie expiration time. You need to set this attribute when saving the cookie on a local computer.

Domain: indicates the domain in which the cookie is associated. The default value is null.

Haskeys: indicates whether the cookie has a subkey.

HTTPOnly: indicates whether the cookie can be read by the client script. In. net2.0, this setting is always true. However, only ie6.0 can recognize this attribute in the client browser.

Path: indicates the virtual directory of the cookie. The default value is "/", indicating the root directory of the site.

Secure: indicates whether the Cookie needs to be encrypted. If set to true, the cookie will accept SSL encryption.

Version: indicates the version number of the cookie.

Create Forms authentication cookies

After a user passes authentication, Forms authentication cookies are automatically created internally by the forms authentication class. A formsauthenticationticket class is created. The code for creating this class is as follows:

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

Then, if the protection attribute of the forms element is set to all in the web. config file

Or encryption, which encrypts the ticket object and creates a signature. The encryption code is as follows:

String encryptedticket = formsauthentication. Encrypt (ticket );

The following describes how to set the protection attribute to true:

Create a serialized Forms authentication ticket: create this object as a byte array)
Create the form authentication ticket signature. The validation and alidationkey attributes in machinekey set the signature generation algorithm. We use this algorithm to calculate the serialized bytearray and generate the MAC (message authentication code ). The sha1 algorithm is used by default.
Encrypted Forms authentication ticket. At the same time, we will create another serialized object, which is encrypted by the encryption algorithm. This encryption algorithm can also be obtained from the decryption and decryptionkey attributes in the machinekey. In Asp.net 1.1, 3DES encryption is used, while in ASP. net2.0, AES encryption is used.
Create an httpcookie object or generate a cookie's query string (we can only generate a query string when Cookie is not supported). The Code for creating an httpcookie object is as follows:
Httpcookie authcookie = new httpcookie (

Formsauthentication. formscookiename,

Encryptedticket );

The encrypted ticket is added to the httpcookie object.

Set Forms authentication cookie to secure. If forms authentication ticket is configured to use SSL, the attribute of httpcookie. Secure must also be set to true. In this case, the browser can only transmit cookies over HTTPS.
Set HTTPOnly bit. In ASP. net2.0, this attribute is set by default.
Set the attributes of the current cookie. If needed, you can set the path, domain and expires attributes of the current cookie.
Add a cookie to cookiecollection and send it to the client. Response. Cookies. Add (authcookie );
Every time the authentication receives a request, the formsauthenticationmodule obtains an authentication ticket from the client cookie, decodes it, calculates the hash value, and compares the MAC value. This ensures that the cookie is not forged. Finally, verify the expiration time of ticket.

Note that ASP. NET does not depend on the cookie expiration date, because the time can be forged easily.

Role authorization)

In ASP. NET 2.0, Role authorization has been simplified. When you perform authentication on a user or add the role details to the authentication cookie, you do not need to retrieve the role information .. Net Framework 2.0 includes a role management API that allows you to create and delete roles, add users to roles, and delete users from roles. This role management API stores its data in a basic data storage. It accesses this storage through an appropriate role provider for this data storage. The following role providers are included with. NET Framework 2.0 and can be used with form authentication:

• SQL Server. It is the default provider that stores role information in the SQL Server database.
• Authorization Manager (Azman ). The provider uses an Azman policy store in the XML file, Active Directory, or Active Directory Application Mode (Adam) as its role storage. It is usually used in the Intranet or exists scheme, where Windows Authentication and Active Directory are used for authentication.

How to: Use Role manager in ASP. NET 2.0.

Cookieless Form Verification
ASP. NET 2.0 supports cookieless form authentication. This function 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 transmit authentication tickets using cookies.
• Useuri. This value indicates that the formsauthenticationmodule class overrides the URL to transfer the authentication ticket.
• Usedeviceprofile. This value indicates the browser viewing function of the formsauthenticationmodule class. If the browser supports cookies, use cookies. Otherwise, rewrite the URL.

• Autodetect. This value uses a dynamic detection mechanism to instruct the formsauthenticationmodule class to detect whether the browser supports cookies. If the detection logic indicates that the cookie is not supported, rewrite the URL.

If the application is configured to use cookieless form authentication and the formsauthentication. redirectfromloginpage method is being used, the formsauthenticationmodule class automatically sets the form authentication ticket in the URL. The following code example shows the format of a typical URL after Rewriting:

Http: // localhost/cookielessformsauthtest/(f (-example)/test. aspx
The URL section in brackets contains the data that cookies usually contain. ASP. NET deletes the data during request processing. This step is performed by the ASP. net isapi filter instead of in the httpmodule class. If you read the request. Path attribute from A. ASPX page, you will not see any additional information in the URL. If the request is redirected, the URL is automatically rewritten.

Note: It is difficult to ensure the security of the authentication ticket contained in the URL. When security is critical, you should use cookies to store authentication tickets.

Membership and logincontrol (member identity and logon Control)
ASP. NET 2.0 introduces the membership function and a set of Logon web server controls, which simplify the implementation of applications that use form authentication.

Membership provides credential storage and management for application users. It also provides a membership API that simplifies the authentication tasks for user creden。 when using form authentication. The membership function is built on the provider model. This model allows implementation and configuration to point to different providers stored by different users. ASP. NET 2.0 includes the following member relationship providers:

• Active Directory membership provider. The provider uses active directory or Active Directory Application Mode (Adam) User storage.

• SQL Server membership provider. The provider uses SQL Server user storage.

You can also add support for user-defined storage. For example, you can add support for other Lightweight Directory Access Protocol (LDAP) directories or other existing public identity storage. To this end, create a custom provider inherited from the abstract base class of membershipprovider.

The ASP. Net Logon control automatically uses membership and form authentication, and encapsulates the logic required to prompt the user to enter creden。, verify the user, recover or replace the password. In fact, the ASP. Net Logon control provides an abstraction layer on form authentication and membership, and replaces most or all of the work that you need to do when using form authentication.

For more information about using the membership function and logon control, see

How to: Use membership in ASP. NET 2.0.

Web farm scenarios (Web field solution)
In the Web field, it is impossible to determine which server will process consecutive requests. If the user is authenticated on one server but the next request is made on another server, the authentication ticket will fail and request the user to perform another authentication.

The validationkey and decryptionkey attributes in the machinekey element are used to hash and encrypt form authentication tickets. The default values of these attributes are autogenerate. isolateapps. These keys are automatically generated for each application and are different on each server. Therefore, authentication tickets encrypted on one computer cannot be decrypted and verified in another computer on the Web farm or in another application on the same web server.

To solve this problem, the validationkey and decryptionkey values on all computers in the Web farm must be the same.

For more information about configuring the machinekey element, see How to: Configure machinekey in ASP. NET 2.0

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.