ASP. net2.0 Forms authentication)

Source: Internet
Author: User
Tags form post http cookie

1. Concepts
Generally, authentication and management of user identities are involved in websites. User Management in websites is divided into four main parts: user identity verification and user access permission verification, user management and user role management.
In the past, when writing user authentication and management functions, developers usually obtain the user identity through session or cookie and query the user identity in the database for authentication. In ASP. NET 2.0, Microsoft is a web page Program You can set authentication methods in the configuration file. Windows Authentication and form authentication are generally used.
There are multiple authentication techniques for Windows authentication, but in essence they are used to verify requests that access server resources and check whether the request header information contains the user's identity information. When Windows authentication is adopted, if the server receives a request without user information, the server will indicate the request in the browser information returned for verification. In this case, the browser will automatically pop up the remote user logon dialog box, asking the user to enter the user name and password on the server, or the user name and password in the domain. This verification method can only be applied to network applications that only run in the internal LAN. In Windows, there are several verification methods, namely basic verification, digest verification, and Windows integration verification. If Windows integrated authentication is used, the browser automatically provides the user logon network identity when sending the request, avoiding the steps for entering the user name and password.
Form authentication is applicable to large websites, because in form Authentication mode, when the server receives a request that does not contain a user identity, the user is automatically directed to the system logon interface. After entering the user name and password, you can access the database to verify whether the user is a legal user of the website. If the user passes the authentication, ASP. NET generates a form authentication tag for the user and sends the tag back to the client. This tag is generally stored in a cookie or embedded in a URL. When a user accesses other webpages of the website, the browser automatically submits the tag to the server to remember the user.
User Authentication and user permission authentication in ASP. net2.0 are implemented using two built-in httpmodules, which are used to verify each request sent by the client to the website resources. The user identity authentication module verifies the user identity tag provided by the browser. If the request does not contain the user identity tag, the user identity authentication module identifies the user as an anonymous user; user permission verification is used to verify whether the user has the permission to access the specified resource. If the user does not have the permission, the request is rejected and handled by the user authentication module, the authentication module directs the user to the logon interface and requires the user to provide an identity with access permissions.
User permission verification in ASP. net2.0 is also divided into two methods: file authentication for Windows Authentication and URL authentication for form authentication. The file authentication method is to use the access control list (ACL) to determine the storage permissions of different windows accounts for different files. The URL authentication method uses Web. config to determine the access permissions of different users and roles for different resources on the website.
Before ASP. net2.0, generally, both user management and role management rely on developers to define data tables for user management and role management in the database, and write them by themselves. Code Implement background database operation code for user logon, adding users, adding roles, and managing users and roles. ASP. net2.0 provides a membership framework for managing user accounts. The advantage of membership is that the framework provides a set of interfaces for managing user accounts, but specific data access and storage operations are implemented through providers, you can configure different providers according to the needs of developers to perform operations on different data sources. ASP. NET comes with two providers for access to Active Directory and SQL server storage. Role management also adopts this method and comes with several providers for Active Directory, and SQL server storage access and role management based on the user's group in Windows (for Windows Authentication Mode)

Ii. Practice

IIS Authentication

ASP. NET authentication is divided into two steps. First, Internet Information Service (IIS) authenticates the user and creates a Windows Token to represent the user. IIS checks the IIS metadatabase settings to determine the Authentication mode that should be used for a specific application. If IIS is configured to use anonymous authentication, a token is generated for the iusr_machine account and used to represent anonymous users. 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 form authentication does not depend on IIS authentication, if you want to use form authentication in ASP. NET applications, configure anonymous access for applications in IIS.

 

 

ASP. NET form Authentication

ASP. NET form authentication occurs after IIS authentication is complete. You can use the forms element to configure form authentication.

Form authentication Configuration

The following configuration file snippet displays the default attribute values for form authentication.



Protection =" all "
timeout =" 30 "
name = ". aspxauth "
Path ="/"
requiressl =" false "
slidingexpiration =" true "
defaulturl =" default. aspx "
cookieless =" usedeviceprofile "
enablecrossappredirects =" false "/>

The following describes the default attribute values:


loginurl points to the custom logon page of the application. The logon page should be placed in the folder requiring Secure Sockets Layer (SSL. This helps ensure the integrity of creden when they are uploaded from the browser to the web server.

protection is set to all to verify the confidentiality and integrity of the ticket with the specified form identity. As a result, the algorithm specified on the machinekey element is used to encrypt the authentication ticket, and use the hash algorithm specified on the same machinekey element for signature.

timeout is used to specify the limited lifetime of the form Authentication Session. The default value is 30 minutes. If a persistent form authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.

name and path are set as values defined in the application configuration file.

set requiressl to false. This configuration means that the authentication cookie can be transmitted through an SSL-encrypted channel. If you are worried about session theft, set requiressl to true.

slidingexpiration is set to true to run the changed session lifetime. This means that the session will be reset periodically as long as the user is active on the site.

defaulturl is set to the default. aspx page of the application.

cookieless is set to usedeviceprofile to specify that the application uses cookies for all browsers that support cookies. If the cookie browser is not supported to access the site, form authentication packages the authentication ticket on the URL.

enablecrossappredirects is set to false, it indicates that form authentication does not support automatic processing of tickets on the query string passed between applications and those passed as part of a form post.

Authorization Configuration

In IIS, enable asynchronous access for all applications that use form authentication. The urlauthorizationmodule class helps ensure that only authenticated users can access the page.

You can use the authorization element to configure the urlauthorizationmodule, as shown in the following example.

<System. Web>
<Authorization>
<Deny users = "? "/>
</Authorization>
</System. Web>

Using this setting will deny all unauthenticated users to access any page in the application. If an unauthenticated user attempts to access a page, the form Authentication Module redirects the user to the logon page specified by the form element's loginurl attribute.

Form authentication control flow


The default. aspx file in the virtual directory where the user requests the application. Because anonymous access is enabled in the IIS metabase, IIS allows this request. ASP. NET confirm authorization elements include <deny users = "? "/> Mark.
 

The server looks for an authentication cookie. If this authentication cookie cannot be found, the user is redirected to the configured logon page (login. aspx), which is based on the loginurl attribute of the forms element. You can use this form to provide and submit creden. Information about the start page is stored in the query string that uses returnurl as the key. The HTTP response is as follows:

302 found location:
Http: // localhost/formsauthtest/login. aspx? Returnurl = % 2 fformauthtest % 2fdefault. aspx

 

The browser requests the login. ASPX page and includes the returnurl parameter in the query string.
 

The server returns the logon page and the HTTP Status Code 200 OK.
 

On the login page, enter the creden and send the page (including the returnurl parameters from the query string) back to the server.
 

The server verifies user creden。 based on a storage, such as the SQL Server database or active directory user store. The Code on the logon page creates a cookie containing the form authentication ticket set for this session.

In ASP. NET 2.0, user creden。 can be verified by the membership system. The membership class provides the validateuser method as follows:

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 Code provided above is used below.
 

For authenticated users, the server redirects the browser to the original URL specified by the returnurl parameter in the query string. The HTTP response is as follows:

302 found location:
Http: // localhost/testsample/default. aspx

 

After redirection, the browser requests the default. aspx page again. This request includes the authentication cookie.
 

The formsauthenticationmodule class detects form authentication cookies and authenticates users. After successful authentication, the formsauthenticationmodule class fills in the current user attribute with information about Authenticated Users (published by the httpcontext object ).
 

Because the server has verified the authentication cookie, it allows access and returns the default. aspx page.
 

Formsauthenticationmodule

ASP. NET 2.0 defines a set of HTTP modules in the computer-level Web. config file, including a large number of authentication modules, as shown below:

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

Each request can only use one authentication module. The authentication module used depends on which authentication mode is specified by the authentication element (usually in the web. config file in the virtual directory of the application.

When the Web. config file contains the following elements, the formsauthenticationmodule class is activated.

<Authentication mode = "forms"/>

The formsauthenticationmodule class constructs a genericprincipal object and stores it in the HTTP context. The genericprincipal object saves a reference to a formsidentity instance. This instance represents the authenticated user. Form authentication should allow you to manage these tasks. If the application has specific requirements (for example, setting the user attribute to a custom class implementing the iprincipal Interface), the application should process the postauthenticate event. After formsauthenticationmodule authenticates the form authentication cookie and creates genericprincipal and formsidentity objects, a postauthenticate event occurs. In this code, you can construct a custom iprincipal object that wraps the formsidentity object and store it in the httpcontext. User attribute.

Note: If this operation is performed, you also need to set iprincipal reference on the thread. currentprincipal attribute to ensure that the httpcontext object and the thread point to the same authentication information.

Form authentication cookie

When formsauthentication. setauthcookie or formsauthentication. redirectfromloginpage method is called, The formsauthentication class automatically creates an authentication cookie.

A typical form authentication cookie includes the following attributes:


Name. This attribute specifies the cookie name.
 

Value. This attribute specifies the cookie value.

In a typical form authentication cookie, this value contains the string representation of an encrypted and signed formsauthenticationticket object. This cookie contains the following attributes:
 

Expires. This attribute specifies the cookie expiration date and time. This value is set only when the Code indicates that a persistent form authentication cookie should be issued.
 

Domain. This attribute specifies the domain associated with the cookie. The default value is null.


Haskeys. This attribute indicates whether the cookie has a subitem.
 
 

HTTPOnly. This attribute specifies whether the cookie can be accessed through client scripts. In ASP. NET 2.0, this value is always set to true. Internet Explorer 6 Service Pack 1 supports this cookie attribute to prevent client scripts from accessing this cookie from the document. Cookie attribute. If you try to access the cookie from a client script, an empty string is returned. The cookie is sent to the server whenever the user browses the web site in the current domain.

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

Path. This attribute specifies the virtual path of the cookie. The default value is "/", indicating the root directory.
 

Secure. This attribute indicates whether the cookie should be transmitted only over HTTPS connections. The secure attribute should be set to true so that the cookie can be protected by SSL encryption.
 

Version. This attribute specifies the cookie version number.
 

Create authentication cookie

Create an authentication cookie using the formsauthentication class, as shown below. After verification, the formsauthentication class creates a formsauthenticationticket object internally by specifying the cookie name, Cookie version, directory path, and cookie issuance date. The cookie expiration date, whether or not the cookie should be retained, and user-defined data (optional ).

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, if the forms element's protection attribute is set to all or encryption, form authentication uses the encrypt method to encrypt and sign Form authentication tickets.

String encryptedticket = formsauthentication. Encrypt (ticket );

The following text shows the process used when the protection property is set to all:


Create a serialized form authentication ticket. The byte array representation of the created ticket.
 

Sign the form authentication ticket. The value of the message authentication code (MAC) in the byte array is calculated 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 the form authentication ticket. The second byte array that has been created is encrypted using the encrypt method of the formsauthentication class. The encrypt method internally uses the algorithms and keys specified by the decryption and decryptionkey attributes on the machinekey element. ASP. NET 1.1 uses the 3DES algorithm by default. ASP. NET 2.0 uses the rinjdael (AES) algorithm by default.
 

Create an HTTP cookie or query string as needed. Then, if form authentication is configured for cookieless authentication, the encrypted authentication ticket is added to the httpcookie object. Use the following code to create the cookie object:

Httpcookie authcookie = new httpcookie (
Formsauthentication. formscookiename,
Encryptedticket );

 

Set the form authentication cookie to secure. If the form authentication ticket is configured to use SSL, The httpcookie. Secure attribute is set to true. This indicates that the browser only sends cookies over HTTPS connections.

Authcookie. Secure = true;

 

Set the HTTPOnly bit. In ASP. NET 2.0, always set this bit.
 

Set appropriate cookie attributes. If necessary, set the path, domain, and expires attributes of the cookie.
 

Add a cookie to the cookie set. Add the authentication cookie to the cookie set that you want to return 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, calculates the hash value, and compares the MAC value, to help ensure that the cookie is not tampered. Finally, verify the expiration time included in the form authentication 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.
 

For more information about how to use role Management APIs, see How to: Use Role manager in ASP. NET 2.0.

 

 

Cookieless form Authentication

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.

 

 

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.

The member identity provides credential storage and management for application users. It also provides a member identity API that simplifies the authentication tasks of user creden。 when using form authentication. This member identity 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 the member identity and form identity authentication, and encapsulates the logic required to prompt the user to enter creden。, verify the user, and restore or replace the password. In fact, the ASP. Net Logon control provides an abstraction layer for form authentication and membership, and replaces most or all of the work that you need to do when using form authentication.

Link: http://edu.itbulo.com/200607/101618.htm

Related Article

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.