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

Source: Internet
Author: User
1. Introduction to membership
2. Settings of membership in SQL server
3. Configure web. config
4. Create user CreateUserWizard Control
5. Log on to the login Control
6. Display the LoginName control of the current user
7. LoginStatus Control for detecting the user's authentication status
8. Displays LoginView controls for different types of users.
9. ChangePassword Control for Password Change
10. PasswordRecovery Control for password retrieval
11. Summary

1. Introduction to membership

Membership is really interesting, convenient, and useful. This article will be introduced to you.
In ASP. NET applications, the Membership class is used to authenticate user creden。 and manage user settings (such as passwords and email addresses ). The Membership class can be used independently or together with FormsAuthentication to create a complete Web application or website user authentication system. 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) store the Membership Information (username, password, email address, and supported data) in Microsoft SQL Server or similar data storage areas.
3) authenticate the users accessing the website. Users can be authenticated programmatically, or a complete authentication system with few or no code is created using the Login control.
4) Manage the password. Including creating, changing, retrieving, and resetting passwords. You can choose to configure ASP. NET membership to require a password to prompt questions and their answers to perform identity verification for 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 to make some settings for the database. 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 = "AspNetSqlMembershipProvi Der "userIsOnlineTimeWindow =" 15 "hashAlgorithmType =" ">
                      <Providers>
                              <Clear/>
                              <Add connectionstringname = "connectionstring" enablepasswordretri = "false" enablepasswordreset = "true" requiresquestionandanswe R = "true" applicationname = "/" requiresuniqueemail = "false" passwordformat = "hashed" maxinvalidpasswordattemp TS = "5" minrequiredpasswordlengt H = "7" minrequirednonalphanumer Iccharacters = "1" passwordattemptwindow = "10" passwordstrengthregulare Xpression = "" name = "aspnetsqlmembershipprovi Der "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 AspNetSqlMembershipProvi.Der. 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: The identifier of the algorithm used to hash the password, or is null to use the default hash algorithm.
ConnectionStringName: The connection name of the membership database.
EnablePasswordRetri: 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 questions 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 member qualification 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 to the invalid or invalid passwords allowed before the user is locked.
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 can be prompted for an invalid password or password 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: Calculate the regular expression of 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 role of the current user 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 role management checks 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 FinishDestinationPageUrl.Attribute. This attribute indicates the target page after you click "continue" after the user is created.

Code:

      <Asp: CreateUserWizard ID = "CreateUserWizard1" runat = "server" ContinueDestinationPageU Rl = "~ /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 template of CreateUserWizard
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: Set 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/>
 

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.