Introduction to ASP. NET authentication mechanism membership

Source: Internet
Author: User

Original address: http://yumincq.blog.163.com/blog/static/50776820108395417220? Fromdm & fromsearch & isfromsearchengine = Yes

Access Control and role management are used in almost all systems, such as creating, modifying, and Deleting Users and roles, assigning roles to users, and managing users in roles. So ms is stored in ASP. NET 2.0 has implemented these functions, so that we do not need to consider this content during development and devote more energy to the development of business logic. This greatly improves the development efficiency. Next we will learn how to use membership.

1. Add Database Support

To use membership, you must first support the database. Therefore, the first step is to create a table structure to store user and role information. Don't worry, Ms has long written the statement for creating a table, and provides a user interface. Let's click it to create the required structure.

The specific operation is as follows: Go to the C: \ WINDOWS \ microsoft. Net \ framework \ v2.0.xxxxx(vs2010's directory is v4.0.xxxx). find aspnet_regsql.exe and double-click it to run it. An interface is displayed and the next step is displayed. On the second page, choose whether to add or remove the table structure. Of course, choose add to continue the next step. In this interface, enter the Server IP address and authentication information. After entering this information, you can select the database to which you want to add the table structure. Note: If the default value is selected, a new database named aspnetdb is created and the table structure is added to the database. The database structure is added in the next step.

2. Web. config Configuration

Now, after adding the table structure, you need to perform some simple configuration in the project. Create a new website in Vs, and then use NotePad to open C: \ WINDOWS \ Microsoft. net \ framework \ v2.0.xxxxx \ config \ machine. in the config file, find system. the membership node under the Web node copies the entire node to the web of the new website. system. in the Web node.

 

The copied code is as follows:

<Membership>
<Providers>
<Add name = "aspnetsqlmembershipprovider"
Type = "system. Web. Security. sqlmembershipprovider, system. Web, version = 2.0.0.0, culture = neutral, publickeytoken = b03f5f7f11d50a3a"
Connectionstringname = "localsqlserver"
Enablepasswordretrieval = "false"
Enablepasswordreset = "true"
Requiresquestionandanswer = "true"
Applicationname = "/"
Requiresuniqueemail = "false"
Passwordformat = "hashed"
Maxinvalidpasswordattempts = "5"
Minrequiredpasswordlength = "7"
Minrequirednonalphanumericcharacters = "1"
Passwordattemptwindow = "10"
Passwordstrengthregularexpression = ""/>
</Providers>
</Membership>

 

The following are the meanings of the main attributes:

Name: name of the data provider. Because we copied it from machine. config, we must change the name to avoid duplicate names.

Type: Data Provider type. If MSSQL is used, it will remain unchanged. If other databases such as Oracle are used, you must create a class to inherit the abstract base class of membershipprovider, override all the abstract methods in it, and write the type here.

Connectionstringname: Specifies the name of a connection string in the <connectionstrings> node.

Applicationname: Application name. membership allows multiple applications to use one database to manage their own user and role information. Each application only needs to configure different applicationnames. Of course, if you want multiple applications to use the same user role information, you only need to set the same applicationname.

Requiresuniqueemail: as the name suggests, whether to provide an unregistered email address when a user registers.

Passwordformat: Password Storage Format. The format of the password stored in the database is clear (unencrypted) and hashed (encrypted using the sha1 algorithm)
Minrequiredpasswordlength: Minimum Password Length.

Minrequirednonalphanumericcharacters: specifies the minimum number of special characters that must be included in a valid password, that is, the number of characters that are not letters or numbers, for example, +-*/, or something, to increase the password strength.

      

Now, let's modify the configuration and add the connection string:

<Connectionstrings>
<Add name = "connectionstring" connectionstring = "Server =.; uid = sa; Pwd = sa; database = aspnetdb"/>
</Connectionstrings>
<System. Web>
<Membership defaultprovider = "mysqlmembershipprovider">
<Providers>
<Add name = "mysqlmembershipprovider"
Type = "system. Web. Security. sqlmembershipprovider, system. Web, version = 2.0.0.0, culture = neutral, publickeytoken = b03f5f7f11d50a3a"
Connectionstringname = "connectionstring"
Enablepasswordretrieval = "false"
Enablepasswordreset = "true"
Requiresquestionandanswer = "true"
Applicationname = "testmembership"
Requiresuniqueemail = "true"
Passwordformat = "hashed"
Maxinvalidpasswordattempts = "5"
Minrequiredpasswordlength = "6"
Minrequirednonalphanumericcharacters = "0"
Passwordattemptwindow = "10"
Passwordstrengthregularexpression = ""/>
</Providers>
</Membership>
</System. Web>

 

The property marked in the highlighted yellow font above is used to tell membership to use the configuration of mysqlmembershipprovider we just added, because the machine. in config, there is an aspnetsqlmembershipprovider. A mysqlmembershipprovider is added to config, and now two configurations are available. Therefore, use the defaultprovider attribute to specify which configuration is used for this website. Then the name of the connection string configuration is specified. Repeated registration is not allowed for an email. The minimum password length is 6, and the password must contain punctuation marks.

3. ASP. NET authentication Configuration

Membership is configured here, but it is not over yet. We also need to configure ASP. NET authentication mechanism as Forms authentication.

 

Additional content:

ASP. NET has three authentication methods:

Forms Verification
Windows Verification
Passport verification

Windows authentication means that users who can access IIS are considered authenticated. You can use the authentication policy that comes with windows to control which page users can access and which cannot access. This is the easiest way to implement access control without having to write much code.

Passport authentication is an authentication service provided by Microsoft. Of course this is charged.

Forms authentication is to add a cookie to the browser when the user logs on, and then detect the cookie every time the user accesses the browser, so as to achieve the purpose of identity authentication.

 

To configure Forms authentication, copy the following code to Web. config:

 

<System. Web>
<Authentication mode = "forms">
<Forms loginurl = "login. aspx"
Protection = "all"
Timeout = "30"
Name = ". aspxauth"
Path = "/"
Slidingexpiration = "true"
Defaulturl = "default. aspx"
Cookieless = "usedeviceprofile"/>
</Authentication>
</System. Web>

  

The following is a description (copied by msdn ):

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.

Set protection 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 the hash algorithm specified on the same machinekey element is used to sign the ticket.

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.

Set Name and path to the value 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 execute the changed session lifetime. This means that the session will be reset periodically as long as the user is active on the site.

Set defaurl URL 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 to indicate 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.

It must be noted that the loginurl and defaulturl attributes: loginurl points to the logon page, when ASP. net determines that the resource requested by the user is not allowed to be accessed anonymously, but when the user is not logged on, Asp. net will automatically jump to the page pointed to by loginurl, when the login is successful, jump back to the original request page. Defaulturl points to the default page. When you directly access the logon page and log on successfully, ASP. NET will jump to the defaulturl page. Other options can be left blank, because there are default values.

This article describes how to configure membership and ASP. NET Forms authentication.

    

After all the basic configurations are complete, we also need to configure which directories are allowed to be accessed anonymously and which are pages that need to be accessed after logon.

First, create an admin folder in the project, add a web. config file to the admin folder, and add the following code under the <system. Web> node:

<Authorization>
<Allow users = "admin"/>
<Deny users = "*"/>
</Authorization>

 

Then, add a page under the Admin directory, visit the page, and check the effect. If you have correctly configured all the content as described in the previous article, you will find that the page is not displayed, instead, the page directed to the loginurl attribute of the <forms> node in <authentication> must be logged on! Isn't that what we need?

 

Now let's explain the meaning of the above Configuration:

<Allow> node: As the name implies, access is permitted. <allow users = "admin"/> means access is allowed by users with the username "admin.

<Deny> node: access is prohibited. Here, a wildcard "*" is used. There are two wildcards: * representing all users, and a "?" Represents all anonymous users. Therefore, <deny users = "*"/> means that access by all users is not allowed. Of course, if it is: <deny users = "? "/> This means that access by anonymous users is not allowed.

It should be noted that all configurations are matched in the order from top to bottom. Once the matching is successful, the matching will not be performed downward. For example:

<Authorization>
<Allow users = "admin"/>
<Allow users = "zhangsan"/>
<Deny users = "*"/>
</Authorization>

ASP. NET first checks the current Login User Name = "admin "? If the value is equal to, the user is not allowed to access the database. If the value is not the same as that of the user name, the user name = "zhangsan" is equal to that of the current logon user. If the value is not the same, access is allowed, read the <deny users = "*"/> Configuration, deny access to all users, jump to the page specified by loginurl and log on again.

 

However, in this case, only permission control at the directory level can be implemented. What should we do if we want to control the access permission of a file? Do you have to put this file in a folder and then add web. config for control? The answer is no. For access control of a single file, ASP. NET also has the corresponding Configuration:

<Configuration>
<Location Path = "A. aspx">
<System. Web>
<Authorization>
<Deny users = "? "/>
</Authorization>
</System. Web>
</Location>
<System. Web>
<Authorization>
<Allow users = "admin"/>
<Allow users = "zhangsan"/>
<Deny users = "*"/>
</Authorization>
</System. Web>
</Configuration>

 

Based on the above configuration, we can go to the <system. add another <location> node on the Web> node (which must be the above), and use the path attribute to specify which file the configuration in the location is. I will not talk much about the specific content. I think everyone can understand it. Note that there can be multiple location nodes. This means that different files in the same directory can have different access permissions.

 

Now, more than half of the configuration has been completed. Another problem is: if we have many users, we need to list all these users in the configuration file. It will be too troublesome to add new users and modify the configurations later! What should I do? A general approach is to introduce the role concept. Assign a role to all users, such as users and Admin. Then we only need to control the access permissions of these roles. After adding a new user, you only need to assign a role to the new user, instead of modifying the configuration. This is really convenient. In fact, membership also provides the role concept, which can be implemented simply by simple configuration.

To implement the role function, it is very simple. We still need to go to machine. <system. web> Find the <rolemanager> node under the node, and then the entire node is copied to the Web. in config, there are usually two <add> subnodes. we can delete one and leave one. The content is as follows:

<Rolemanager>
<Providers>
<Add name = "aspnetsqlroleprovider"
Connectionstringname = "localsqlserver"
Applicationname = "/"
Type = "system. Web. Security. sqlroleprovider, system. Web, version = 2.0.0.0, culture = neutral, publickeytoken = b03f5f7f11d50a3a"/>
</Providers>
</Rolemanager>

 

This configuration is relatively simple. The configuration is the same as the previous configuration. Slightly modify:

<Rolemanager enabled = "true" defaultprovider = "myaspnetsqlroleprovider">
<Providers>
<Add name = "myaspnetsqlroleprovider"
Connectionstringname = "connectionstring"
Applicationname = "testmembership"
Type = "system. Web. Security. sqlroleprovider, system. Web, version = 2.0.0.0, culture = neutral, publickeytoken = b03f5f7f11d50a3a"/>
</Providers>
</Rolemanager>

Note: This rolemanager has an extra attribute enable = "true". This is because role management is disabled by default, so we must set this attribute to enable.

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.