Asp.net 2.0 course membership and role management

Source: Internet
Author: User
Tags form post http cookie send cookies

Respect the author. Keep the words www.it55.com.

Every complete website management system should include user management and role management, including user registration, password modification, user logon, identity verification, and other functions. In the Asp.net 1. x era,ProgramFor these common functions, we have repeatedly done repetitive work. Today's Asp.net 2.0 encapsulates these common controls and mechanisms for us, bringing us a lot of convenience. In the next two sections, we will learn about this content.
This section describes the membership and role management section of Asp.net 2.0.

1. Asp.net authentication method
There are four authentication methods for Asp.net: Windows authentication, passport authentication, none authentication, and forms authentication. In our web application development, forms authentication is the most commonly used, so here we only involve forms authentication.
In addition to storing the authentication information of the Asp.net 2.0 website in cookies as a regular program, it also provides a scheme for saving the session with a URL, that is, the "no-Cookie Session function ". The "no-Cookie Session function" is designed to prevent the client from being unable to perform authentication because it shields the cookie function. However, this function also brings security risks, therefore, we recommend that you use the Cookie Session scheme.
For forms-based authentication, you must set the Web. config website configuration file and the <forms> child element of the <authentication> element under <system. Web>:

<Authentication mode = "forms">
<Forms name = ". vs2005_form" loginurl = "~ /Security/login. aspx "defaulturl = "~ /Default. aspx"
Protection = "all" timeout = "30" Path = "/" requiressl = "false"
Slidingexpiration = "true" enablecrossappredirects = "false"
Cookieless = "usedeviceprofile">
</Forms>
</Authentication>

<Forms> the attributes of an element are described as follows:
1) cookieless-authentication can store forms authentication tickets in cookies or URLs without cookies. Valid values:
· Usedeviceprofile-default value indicates that ASP. NET determines the location of the storage ticket based on the pre-calculated browser configuration file.
· Autodetect-enables ASP. NET to dynamically determine whether the browser supports cookies.
· Useuri-enforce no cookie ticket
· Usecookies-a cookie ticket is enforced.
2) defaulturl-specifies the default URL to which the request will be redirected after successful logon.
3) domain-specifies the domain attribute value of httpcookie that contains forms authentication tickets. Explicitly setting this attribute allows applications to share the same cookie, provided that these applications share a public part of a DNS namespace (for example, if the domain attribute is set to cnblogs.com ", then webabcd.cnblogs.com and dudu.cnblogs.com can share a cookie ).
4) enablecrossappredirects-Forms authentication allows you to pass Forms authentication tickets between applications in the form of query string variables or form post variables. Setting this attribute to true enables formsauthenticationmodule to extract tickets from query strings or form post variables.
5) loginurl-specifies the URL to which requests from unauthenticated users will be redirected. The URL can be on the same computer or remote computer. If it is on a remote computer, the decryptionkey and validationkey attributes in the machinekey configuration element on both computers must use the same value.
6) name-the name of the HTTP cookie used for authentication. NOTE: If multiple applications need to use the form-based authentication service on one computer, and each application wants the application to isolate Forms authentication cookies, each application should be configured with a unique cookie value. To avoid generating dependencies in URLs, Asp. net also uses "/" as the path value to send these cookies back to each application on the site.
7) path-the path used to send the cookie. The default value is "/" to avoid difficulties caused by mismatch between upper and lower case characters in the path, because the browser is case sensitive when returning cookies. Applications in the shared server environment should use this command to maintain private cookies. (They can also use the API to specify a path at runtime to send cookies .)
8) Protection-the method used to protect cookie data. Valid values:
· All-use both data verification and encryption to protect cookies. Verify the configured data Algorithm Is based on the <machinekey> element. If the key is long enough (48 characters), AES encryption is used by default. All is the default (and recommended) value.
· None-use cookies only for websites with low security requirements for personalized settings. Encryption and verification can be disabled. Although you need to be cautious when using cookies in this way, this setting provides the best performance for any method that uses. NET Framework for personalized settings.
· Encryption-encryption of cookies using AES, tripledes, or DES, but data verification is not performed on cookies. These cookies are vulnerable to carefully selected plain text attacks.
· Validation-do not encrypt the cookie content, but verify that the cookie data has not been changed during transmission. To create a cookie, verify that the key is connected to the cookie data in the buffer, calculate the Mac and append it to the output cookie.
9) requiressl-if it is set to true, Forms authentication sets the Security bit of the forms authentication cookie. Compatible browsers only send cookies back to ASP. NET over SSL connections. Note: This setting is invalid if no cookie Forms authentication is used.
10) slidingexpiration-if set to true, Forms authentication regularly updates the lifetime of Forms authentication tickets. This operation is performed regardless of whether the ticket is contained in a cookie or in a URL without a cookie.
11) timeout-time (in the unit of integer minutes). After the time, the cookie will expire. The default value is 30. The timeout attribute is an adjustable value. It is calculated from the time when the last request is received. It will expire in n minutes. To avoid negative impact on performance, and to avoid multiple browser warnings from applications that have opened the cookie warning, the cookie is updated when the timeout time is over half. (This means that loss of precision may occur in some cases .) # P # paging title # e #

2. user authorization.
In the Asp.net 2.0 program, we can configure the Web. config file to control access permissions. The configuration method is as follows:

<Authorization>
<Allow verb = "Post" users = "2abcd@gmail.com"/>
<Allow roles = "admin"/>
<Deny users = "*"/>
<Allow verb = "get" users = "ABC, XYZ"/>
<Deny users = "? "/>
</Authorization>

Note: you can write the configuration of authorized users and role settings in a folder. The configuration only applies to the folder and automatically inherits the configuration from the outside.
Allow-allow
Deny-reject
Users-users (multiple users are separated by commas)
Roles-roles (multiple roles are separated by commas)
Verb-specify the HTTP method, post or get
*-All Users
? -Anonymous (unauthenticated) Users

We can also authorize the role by path:

<Location Path = "folder">
<System. Web>
<Authorization>
<Deny users = "? "/>
<Allow users = "*"/>
</Authorization>
</System. Web>
</Location>

<Location Path = "ABC. aspx">
<System. Web>
<Authorization>
<Allow roles = "Administrators"/>
<Deny users = "*"/>
</Authorization>
</System. Web>
</Location>

<Location> the path attribute of an element can be a folder or a file.

3. Member Qualification Management
Membership and membershipuser are important members of the membership management API. Using them, we can implement user verification, management, information retrieval, and other functions. But before using them, we need to modify web. config to configure them. Configuration example:

<Membership defaultprovider = "sqlmembershipprovider">
<Providers>
<Clear/>
<Add name = "sqlmembershipprovider"
Type = "system. Web. Security. sqlmembershipprovider, system. Web, version = 2.0.0.0, culture = neutral, publickeytoken = b03f5f7f11d50a3a"
Connectionstringname = "sqlconnectionstring"
Enablepasswordretrieval = "false"
Enablepasswordreset = "true"
Requiresquestionandanswer = "false"
Applicationname = "/"
Requiresuniqueemail = "false"
Passwordformat = "hashed"
Maxinvalidpasswordattempts = "3"
Minrequiredpasswordlength = "3"
Minrequirednonalphanumericcharacters = "0"
Passwordattemptwindow = "10"
Passwordanswerattemptlockoutduration = "15"
Passwordstrengthregularexpression = ""/>
</Providers>
</Membership>

Enablepasswordretrieval-whether the user password can be retrieved (always false)
Enablepasswordreset-whether to allow users to reset their passwords
Requiresquestionandanswer-whether to require a password prompt and answer when creating a user # P # paging title # e #
Applicationname-name of the application for the custom membership provider
Requiresuniqueemail-whether the email address must be unique
Passwordformat-format of the Stored Password
Maxinvalidpasswordattempts-number of failures allowed when a user answers a password reset question
Minrequiredpasswordlength-Minimum Password Length
Minrequirednonalphanumericcharacters-the minimum number of special characters that a valid Password must contain
Passwordattemptwindow-the duration (in minutes) for tracking the number of consecutive failures to correctly answer password reset questions)
Passwordanswerattemptlockoutduration)
Passwordstrengthregularexpression-Regular Expression used to verify the password

Some functions of the membership classCodeExample:
Create a new user:

Try {
Membership. createuser ("name", "password", "mail ");
}
Catch (membershipcreateuserexception E)
{
// Failed
Switch (E. statuscode)
{
Case membershipcreatestatus. duplicateusername:
......;
Case membershipcreatestatus. duplicateemail:
......;
Case membershipcreatestatus. invalidpassword:
......;
Default:
......;
}
}

Logon Verification:

If (membership. validateuser (username. Text, password. Text ))
Formsauthentication. redirectfromloginpage (username. Text, rememberme. Checked );

Available Methods: createuser (create user) deleteuser (delete user) generatepassword (generate password) getallusers (get user) getuser (View A User) updateuser (modify user) validateuser)

Sample Code for implementing some functions of the membershipuser class:
Pending logon permissions:

If (membership. validateuser (username. Text, password. Text )){
Membershipuser user = membership. getuser (username. Text );
User. Comment = "0"; // record the number of logins
Redirectfromloginpage (username. Text, rememberme. Checked );
}
Else {
Membershipuser user = membership. getuser (username. Text );
If (user! = NULL ){
String COUNT = convert. toint32 (user. Comment) + 1;
User. Comment = count. tostring ();
}
}

Some of its methods and attributes:
Attribute: Comment creationdate email lastlogindate lastpasswordchangeddate userid Username
Method: changepassword-questionandanswer GetPassword resetpassword

4. role management
To Manage Roles, you must first configure the <rolemanager> Configuration section in the web. config file:

<Rolemanager defaultprovider = "sqlroleprovider"
Enabled = "true"
Cacherolesincookie = "true"
Cookiename = ". vs2005_role"
Cookietimeout = "30"
Cookiepath = "/"
Cookierequiressl = "false"
Cookieslidingexpiration = "true"
Cookieprotection = "all">
<Providers>
<Add
Name = "sqlroleprovider"
Type = "system. Web. Security. sqlroleprovider"
Connectionstringname = "sqlconnectionstring"
Applicationname = "/"/>
</Providers>
</Rolemanager>

Cacherolesincookie: checks the cookie before using the role provider to check the role list in the data source when verifying whether a user is in a specific role. If the value is true, the list of role names in the current user's cookie is cached; otherwise, the value is false. The default value is false. # P # paging title # e #
Cookiename: name of the cookie that stores the role name. The default value is ". aspxroles ".
Cookiepath: Specifies the Cookie Path of the role name. The default value is "/".
Cookieprotection: Specifies one of the cookieprotection enumeration values. The default value is all.
Cookierequiressl: Specifies whether the role name Cookie needs to be sent to the server using SSL. If this parameter is set to true, the role name Cookie needs to be sent to the server using SSL. The default value is false.
Cookieslidingexpiration: Specifies whether to regularly reset the expiration date and time of the role name Cookie. If it is set to true, the cookie expiration date and time are initially set to the addition of the current date and time and cookietimeout value (minutes. When users continue to actively use ASP. NET applications, the cookie expiration date and time will be automatically updated when the remaining time is less than half of the cookietimeout value. For more information, see expires. The default value is true.
Cookietimeout: the time (in minutes) before the cookie expires ). The default value is "30" (minutes ).
Createpersistentcookie: Specifies whether the role name Cookie is a session cookie. That is, the cookie is lost when the browser is disabled. If set to true, the role name Cookie is a persistent cookie that can be used across multiple browser sessions. Set the expiration date and time of the persistent cookie to the addition of the current date and time and cookietimeout value (minutes. The default value is false.
Defaultprovider: name of the default role provider. For more information, see provider. The default value is "aspnetsqlroleprovider ".
Domain: Specifies the Domain value of the role name Cookie. The default value is the default value of httpcookie. The value is an empty string ("").
Enabled: Specifies whether to enable role management. If this parameter is set to true, role management is enabled. In the machine. config file, the default value is false.
Maxcachedresults: specifies the maximum number of role names cached in the role cookie. The default value is 25.

Role Management APIs include many classes, such as roles, roleprincipal, rolemanagereventargs, and rolemanagermodule. The roles class is the most important and commonly used.
Common roles Methods: addusertorole createrole deleterole getrolesforuser (view User Roles) getusersinrole isuserinrole removeuserfromrole

Because this section contains a large number of related attributes, methods, and events, you can only put out frequently-used items as much as possible. If you do not understand anything, search for them and Google them.

Member qualificationsSource code:
Upload/2007_05/07051722446157.rar
Role management source code:
Upload/2007_05/07051722442920.rar
Note: The above code is taken from the book ASP. NET 2.0 Development Guide. Thanks to the original author.

Next section: logon controls

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.