Use membership (system. Web. Security) for role and permission management)

Source: Internet
Author: User
Tags sendmsg tagname
1. Introduction to membership
2. Membership in SQL Server Settings in
3. Configuration Web. config
4. Create the createuserwizard control.
5. log on to the login control.
6. display the loginname control of the current user
7. Check the loginstatus control of the user's authentication status
8. Present loginview controls for different categories of users with different content
9. Change the password's changepassword Control
10. Self-Help password retrieval passwordrecovery Control
11. Conclusion

1. Introduction to membership

Membership is really interesting, convenient, and useful. This article will be introduced to you.
In ASP . NET application Program The membership class is used to verify user creden and manage user settings (such as passwords and Email Address ). The membership class can be used independently or together with formsauthentication to create a complete Web application or Website . The login control encapsulates the membership class to provide a convenient user authentication mechanism.
The membership class provides the following functions:
1) create a new user.
2) Transfer the Membership Information (username, password, email address, and Support) Data ) Storage In Microsoft SQL Server or other similar data storage areas.
3) authenticate the users accessing the website. Users can be authenticated programmatically, or a login control can be used to create Code Or a complete authentication system without code.
4) Manage the password. Including creating, changing, retrieving, and resetting passwords. Available configurations ASP. NET To ask a password to prompt a question and answer, you can perform authentication on the password reset and retrieval requests of users who forget the password.
By default, ASP. NET membership supports all ASP. NET applications. The default membership provider is sqlmembershipprovider and is specified in the computer configuration with the name aspnetsqlprovider. The default instance of sqlmembershipprovider is a local instance connected to Microsoft SQL Server.

2. settings of membership in SQL Server

To use membership, you need Database Some settings are made. Those who have used membership know that there are some inherent tables, views, and stored procedures in the database. Our own tables do not have these things.
Finally, we can use the Wizard to create them, that is, aspnet_regsql.exe, which is generally located at: C: \ WINDOWS \ Microsoft. NET \ framework \ v2.0.50727 (here I am)
It can create options in the database or remove these settings.
Before running this program, I created an empty database in SQL server2005: membershipdemo.
After establishing membershipdemo, run aspnet_regsql.exe and specify membership as membershipdemo.
[Attach] 34768 [/Attach]
After completion, the empty database will have a lot of content, but the specific content is not required for the moment. Continue with the subsequent content.
[Attach] 34769 [/Attach]

3. Configure web. config

Web. config also needs to be modified.
Add an authentication node under the system. Web Node
Since membership is used for member qualification management, of course, login authentication is required, so first add a form authentication.

Code:
<Authentication mode = "forms">
<Forms loginurl = "login. aspx" name = ". aspxlogin"/>
</Authentication>

Add a membership node to the system. Web node.

Code:
<Membership defaultprovider = "aspnetsqlmembershipprovider" userisonlinetimewindow = "15" hashalgorithmtype = "">
<Providers>
<Clear/>
<Add connectionstringname = "connectionstring" enablepasswordretrieval = "false" enablepasswordreset = "true" Success = "true" applicationname = "/" requiresuniqueemail = "false" passwordformat = "hashed" Success =" 5 "minrequiredpasswordlength =" 7 "minrequirednonalphanumericcharacters =" 1 "passwordattemptwindow =" 10 "passwordstrengthregularexpression =" "name =" aspnetsqlmembershipprovider "type =" system. web. security. sqlmembershipprovider, system. web, version = 2.0.0.0, culture = neutral, publickeytoken = b03f5f7f11d50a3a "/>
</Providers>
</Membership>

Attribute description:
Defaultprovider: name of the provider. The default value is aspnetsqlmembershipprovider. If you have multiple providers, it is wise to specify a default value.
Userisonlinetimewindow: specify the number of minutes that the user is considered online after the date/timestamp of the last activity.
Hashalgorithmtype: Used to hash passwords Algorithm Or empty to use the default hash algorithm.
Connectionstringname: connection name of the membership database.
Enablepasswordretrieval: indicates whether the current membership provider is configured to allow users to retrieve their passwords.
Enablepasswordreset: indicates whether the current membership provider is configured to allow users to reset their passwords.
Requiresquestionandanswer: indicates whether the default membership provider requires the user to answer the password prompt question during password reset and retrieval.
Applicationname: Application name.
Requiresuniqueemail: indicates whether the membership provider is configured to require each user name to have a unique email address.
Passwordformat: indicates the format of the password stored in the membership data storage area. Values include clear, encrypted, and hashed. Clear passwords are stored in plain text, which improves the performance of storing and retrieving passwords, but are less secure. When the security of data sources is threatened, such passwords are easily read. The encrypted password is encrypted during storage and can be decrypted during password comparison or retrieval. This type of password requires additional processing during storage and retrieval, but it is relatively secure and is not easy to obtain when the security of the data source is threatened. When the hashed password is stored in the database, it uses a one-way hash algorithm and a randomly generated salt value for hash processing. When a password is verified, the password is hash calculated using the salt value in the database for verification. The hash password cannot be retrieved.
Maxinvalidpasswordattempts: number of attempts to prompt questions and answers before an invalid or invalid password is allowed to lock a qualified user.
Minrequiredpasswordlength: minimum length required by the password.
Minrequirednonalphanumericcharacters: the minimum number of special characters that a valid Password must contain.
Passwordattemptwindow: the maximum number of minutes that a question answer attempt is prompted for an invalid or invalid password that is allowed before the user is locked. This is an additional measure to prevent unknown sources from repeatedly trying to guess the password of a Member-qualified user or the password prompts the answer to the question.
Passwordstrengthregularexpression: the regular expression used to calculate the password.

After configuring web. config for membership, configure its role management rolemanager.
Also in system. Web

Code:
<Rolemanager enabled = "true" cacherolesincookie = "true">
<Providers>
<Clear/>
<Add connectionstringname = "connectionstring" applicationname = "/" name = "aspnetsqlroleprovider" type = "system. web. security. sqlroleprovider, system. web, version = 2.0.0.0, culture = neutral, publickeytoken = b03f5f7f11d50a3a "/>
</Providers>
</Rolemanager>

Attribute description:
Cacherolesincookie: indicates whether the current user's role has been cached in a cookie.
When the cacherolesincookie attribute is set to true in the configuration file, the role information of each user is stored in a cookie on the client. When the role management check determines whether a user belongs to a specific role, it checks the role cookie before calling the role provider to check the role list in the data source. The cookie is dynamically updated on the client to cache recently verified role names.
Web. config is configured almost.
Really step into the question.

4. Create the createuserwizard control.

Create An ASPX page in vs2005 named createuserwizard. aspx.
Drag a createuserwizard control from the toolbox and set the finishdestinationpageurl attribute. This attribute indicates the target page after you click "continue" after the creation is complete.

Code:
<Asp: createuserwizard id = "createuserwizard1" runat = "server" continuedestinationpageurl = "~ /Default. aspx ">
</ASP: createuserwizard>

Currently, no settings are made. You can see it in the design view of vs2005.

Test it first!

Submit. the following result is displayed:
[Attach] 34772 [/Attach]
Therefore, after Correctly Setting membership, the registered users can use it immediately.
Default Value of createuserwizard Template
You can also create your own template
Vs2005 can help you convert
You can modify it. This is the case after conversion.
There will be a lot of code

5. log on to the login control.

Createuserwizard can be directly dragged out for use, and the same is true for the login control.
Put a login in the page, the code is very simple

Code:
<Asp: Login ID = "login1" runat = "server" destinationpageurl = "~ /Admin/default. aspx "passwordrecoverytext =" retrieve password "passwordrecoveryurl =" passwordrecovery. aspx ">
</ASP: Login>

Attribute explanation:
Destinationpageurl: Set the URL of the page displayed to the user when the logon attempt is successful.
Passwordrecoverytext: Set the text of the password recovery Page Link.
Passwordrecoveryurl: Specifies the URL of the password recovery page. If you forget your password, click this link to retrieve it.
You can also write a template by yourself.

The test is not busy this time.
Wait for the following controls!

6. display the loginname control of the current user

This control is simple and used to present the user name.

Code:
<Asp: loginname id = "loginname1" runat = "server" formatstring = "Hello, {0}. Your current identity is: Registered User"/>

If you are currently logged on to blueidea, it displays "Hello, blueidea, your current identity is: Registered User ".

7. Check the loginstatus control of the user's authentication status

It can be said that it is the simplest control.

Code:
<Asp: loginstatus id = "loginstatus1" runat = "server"/>

It contains two states:
1) You have logged on to the website.
2) You have logged out of the website.
After the user logs out, a "login" link is provided. You can click this link to log on. After the user logs in, the control automatically changes to "logout" status.

8. Present loginview controls for different categories of users with different content

All the logon controls can be used directly. However, we can do more.

Code:
<Asp: loginview id = "loginview1" runat = "server">
<Loggedintemplate>
<Asp: loginname id = "loginname1" runat = "server" formatstring = "Hello, {0}, you have logged on. "/>
</Loggedintemplate>
<Anonymoustemplate>
<Asp: Label id = "label2" runat = "server" text = "You have not logged on, please"> </ASP: Label> <asp: loginstatus
Id = "loginstatus1" runat = "server"/>
</Anonymoustemplate>
<Rolegroups>
<Asp: rolegroup roles = "admin">
<Contenttemplate>
<Asp: loginname id = "loginname1" runat = "server" formatstring = "Hello, {0}. Your current identity is administrator"/>
<Br/>
You can access: <asp: hyperlink id = "hyperlink1" navigateurl = "User/default. aspx" runat = "server"> User/default. aspx </ASP: hyperlink>
<Br/>
You can also access: <asp: hyperlink id = "hyperlink2" navigateurl = "admin/default. aspx" runat = "server"> admin/default. aspx </ASP: hyperlink>
<Br/>
<Asp: loginstatus id = "loginstatus3" runat = "server"/>
</Contenttemplate>
</ASP: rolegroup>
<Asp: rolegroup roles = "member">
<Contenttemplate>
<Asp: loginname id = "loginname1" runat = "server" formatstring = "Hello, {0}. Your current identity is: Registered User"/>
<Br/>
You can access <asp: hyperlink id = "hyperlink1" navigateurl = "User/default. aspx" runat = "server"> User/default. aspx </ASP: hyperlink>
<Br/>
You cannot access <asp: hyperlink id = "hyperlink2" navigateurl = "admin/default. aspx" runat = "server"> admin/default. aspx </ASP: hyperlink>
<Br/>
<Asp: loginstatus id = "loginstatus2" runat = "server"/>
</Contenttemplate>
</ASP: rolegroup>
</Rolegroups>
</ASP: loginview>

As you can see, there are three templates: loggedintemplate, anonymoustemplate, and rolegroup.
If the loggedintemplate template is defined, the user will see the content in the template, unless the user belongs to another role group and the role group is defined in the template already in rolegroups.
When an anonymous user accesses the site, the content in anonymoustemplate is displayed to the user.
The role is enabled in the web. config we configured earlier. Now we define a template for the admin role. You can find it in the code above.
Now, we can test the effect.

We can see that we have not logged on yet, and the anonymoustemplate content is displayed in front of us. Loginstatus displays the "Logon" status.
Let's log on, register a user, and log on.

Loggedintemplate does not work, but the Member role Template takes effect. This is because, in fact, we set it in createuserwizard, and the new user is directly included in the member role group after registration.
Add a simple sentence to the createduser event of createuserwizard:

Code:
Protected void createuserwizardinclucreateduser (Object sender, eventargs E)
{
Roles. addusertorole (createuserwizard1.username, "member ");
}

Let's explain the above "you can visit ......" What does it mean.
Before that, I have actually added two roles: Member and Admin.
Adding a role is simple:
In vs2005, choose website> ASP. NET configuration> Security> Create or Manage Roles.
With the above cooperation, we add a role named "admin ".

Then select "create access rule" to create an access rule.
Create the following rule for the admin file, as shown in:

The member group and anonymous users are denied. Only users in the admin group can access the admin folder.
Create the following access rules for the user folder.

Reject anonymous users and allow users in the member and Admin groups.

After the newly registered users log on, they can access the files in the user folder.

However, if you access the admin folder, it will be directed to the logon page.

9. Change the password's changepassword Control

Use it to change the password.

Code:
<Asp: changepassword id = "changepassword1" runat = "server">
</ASP: changepassword>

You can change the password without setting it.
[Attach] 34780 [/Attach]

10. Self-Help password retrieval passwordrecovery Control

What should I do if I forget my password? I can retrieve it myself!
However, Web. config has to be configured before.
Create a system.net node on the same-level node in system. Web. The details are as follows:

Code:
<System.net>
<Mailsettings>
<SMTP deliverymethod = "network" from = "* @ 126.com">
<Network defaultcredentials = "false" host = "smtp.126.com" Password = "*" Port = "25" username = "* @ 126.com"/>
</SMTP>
</Mailsettings>
</System.net>

We used a mailbox of 126, and the username and password were omitted.
Create passwordrecovery. aspx and place it in the passwordrecovery control.

Code:
<Asp: passwordrecovery id = "passwordrecovery1" runat = "server">
</ASP: passwordrecovery>

Test:

Open the email address you entered during registration.

We can use the new password to log on to the site.

11. Conclusion

before the contact, membership was mysterious. After the contact, it was not difficult to find out, and it worked perfectly with the login control series. If you want to quickly build a user management platform, this is a good choice, and is the first choice for scammers.
If you suspect that the MS control is too ugly and does not matter, because it has a variety of templates, You can implement the interface you want to see through custom templates.
however, membership is designed to suit the majority of scenarios. Therefore, it is also a kind of golden oil practice, which may not fully match the features you want. However, let's take a look at its practice, isn't it a good thing to learn about its database design?

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.