Extending membership service with good VS2005

Source: Internet
Author: User
Tags config functions hash interface new features string format trim visual studio
One of the best new features in ASP.net 2.0 is the new membership service, which provides an Easy-to-use API for creating and managing user accounts. ASP.net 1.x has introduced form authentication on a large scale, but it still requires that you write a significant amount of code to perform forms authentication in the actual operation. The membership service fills the gap in the ASP.net 1.x Forms Authentication Service and makes implementing forms authentication much simpler than it used to be.

The membership API is exposed through two new classes: Membership and MembershipUser. The former contains static methods for creating users, validating users, and accomplishing other work. MembershipUser represents a single user that contains methods and properties for retrieving and changing passwords, obtaining the last logon date, and accomplishing similar work. Through these two new classes, we can not write a line of code to facilitate the completion of user management. But in the actual development process, absolutely can not meet the needs of our daily development. After the development of daily projects and the search of data on the web, they are listed as follows:

The default types of databases are SQL Express, and we often use SQL Sever 2000 or SQL Server 2005 in actual development, and then we need to modify the database type.

Microsoft has provided us with a aspnet_regsql command to modify the default database. Open the Visual Studio 2005 command prompt, enter Aspnet_regsql, and follow the prompts step-by-step.

When you open the database, you can find multiple stored procedures that begin with a series of "aspnet_", which is the stored procedure we need to use membership.

The Iis,[property]→[asp.net]→[edit configuration is turned on:

[General], the connection parameter localsqlserver in the normal SQL connection string format.

[Authentication], the mode is forms, the management provider's minrequirednonalphanumericcharacters is 0, then you can remove the default abnormal required input letters, numbers and other combinations of passwords secure. This step can also modify the minimum password length and maximum length, and so on.

After this step, the system will automatically configure the rules we need in web.config. It is convenient to modify the web.config can be through this graphical tool.

Second, because of the login control and Membership class, only provide a simple user information input, can not meet the needs of our project. For example: We want to register when the user entered the QQ number, telephone number, home address. Then the default is no way to solve. I've got two solutions here. I used it in different projects. The pros and cons are judged by themselves.

1, use profile. There are many online tutorials for such methods. Not to repeat the narrative, to avoid the suspicion of earning royalties:). Here is only a partial explanation that is not available on the Internet.
Because membership can only list the username of the specified group, but not the other details, we often need to modify the other information in the group at the same time in the actual use. I am using the method of constructing the DataTable myself. See Code:

public static DataTable Listuser (string userroles)//list user information for the specified group
{
string[] users = Roles.getusersinrole (userroles);
Lists the users under the specified group
DataTable dt = new DataTable ();
Dt. Columns.Add ("username", System.Type.GetType ("System.String"));
Dt. Columns.Add ("QQ", System.Type.GetType ("System.String"));
Dt. Columns.Add ("Phone", System.Type.GetType ("System.String"));
Dt. Columns.Add ("Address", System.Type.GetType ("System.String"));
Dt. Columns.Add ("Email", System.Type.GetType ("System.String"));
The above constructs a data table
foreach (String i in users)
{
DataRow dr = dt. NewRow ();
MembershipUser mu = membership.getuser (i);
Get basic User Information
ProfileCommon p = profile.getprofile (i); Get profile information for a user
Dr[0] = mu. Username
DR[1] = p. QQ;
Profile is strongly typed and can be easily added through perception.
DR[2] = p. phone;
DR[3] = p. address;
Dr[4] = mu. Email
Dt. Rows.Add (DR);
Dt. AcceptChanges ();
}
return DT;
}
public static void DeleteUser (string username)/delete specified user
{
Membership.deleteuser (username);
The system will automatically delete the specified user information under profile
}
public static void UpdateUser (string username)/update specified user
{
ProfileCommon p = profile.getprofile (i);
Get profile information for a user
P. phone= "Telephone";
P. address= "address;
P. qq= "QQ number";
P.save ();
Save the changes you made.
}
2, custom a membershipinfo table, with Membership System Standard Association. Write your own SQL statements to query, modify and other functions.

List users for a specified group
SELECT * FROM aspnet_membership inner join aspnet_users on
Aspnet_membership.userid=aspnet_users.userid left join MemberInfo on Aspnet_membership.userid=memberinfo.userid
Where aspnet_membership.userid= (select UserID from Aspnet_usersinroles inner JOIN
Aspnet_roles on Aspnet_usersinroles.roleid=aspnet_roles.roleid where rolename= ' admin ')

  
Delete, modify and other functions are relatively simple, here is not described. The membership CreateUser method can be established and then written to the MemberInfo table using SQL statements.

For the user to build, we can take the extended CreateUserWizard control, or write our own login interface.

1, take the extended CreateUserWizard control, we can use its template column, at this point need to pay attention to is: User name, password, prompt questions, answer questions, Email, their ID must be username,password,question, Answer,email Otherwise there will be an error, and validation controls are not available at this time. Suspected to be a bug in the IDE.

As shown below, the style that we define well should be:

<WizardSteps>
<asp:createuserwizardstep runat= "Server" Custom code section <ContentTemplate>
</ContentTemplate>
</asp:CreateUserWizardStep>
</WizardSteps>
Code section:
protected void Createuserwizard1_createduser (object sender, EventArgs e)
{
Because the system will automatically create the basic information table, so we only need to change the profile or MembershipInfo standard.
Roles.addusertorole (Createuserwizard1.username, "shop");
Add a user to the appropriate group
ProfileCommon p = (ProfileCommon) profilecommon.create (Createuserwizard1.username, true);
P. QQ = ((TextBox) CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl ("QQ")). Text.trim ();
P.address= ((TextBox) CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl ("Address"). Text.trim ();
P.phone = ((TextBox) CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl ("Phone")). Text.trim (); P.save ()//Save changes
}
2, to take their own writing UI, personal recommendations to use this method. Flexibility is greater and you can use 2005 of powerful validation controls.

The page section is simpler and less declarative. The code section is described in detail below.

At this point we need to use the Membership CreateUser () method. We will not introduce the grammar. He returns a MembershipCreateStatus enumeration class based on the results of the user creation, which details all the error messages that create the user's unsuccessful. We only need to be based on his value, we can return to the interface corresponding hints, such as: User name already exists, e-mail already exists, and so on.

For the custom user Information section we can still take a profile or a custom MembershipInfo table method.

Lists the methods by which profile establishes the user. SQL statements are simpler and skip writing.

protected void Button1_Click (object sender, EventArgs e)
{
MembershipCreateStatus status;
MembershipUser NewUser = Membership.CreateUser (username. Text.trim (), Password.Text.Trim (), Email.Text.Trim (), Question.Text.Trim (), Answer.Text.Trim (), true, out status);
Use membership to build the user and return the build result to MembershipCreateStatus

if (NewUser = null)//No new user, it means an error.
{
GetErrorMessage (status);
Call GetErrorMessage function, return verbose error message
} else {
Roles.addusertorole (Newuser.username, "Jiancai");
Add a user to the appropriate group ProfileCommon
p = (ProfileCommon) profilecommon.create (Newuser.username, true);
P.QQ = QQ. Text.trim ();
p.address= address. Text.trim ();
P.phone= phone. Text.trim ();
P.save ();
}
}
public void GetErrorMessage (MembershipCreateStatus status)
{
Switch (status)
{
Case MembershipCreateStatus.DuplicateUserName:DisplayAlert ("The current user already exists, please select Again");
Break
For the rest of the error messages, see the MSDN MembershipCreateStatus enumeration class.
Default:displayalert ("Registered 00000000 users failed, please check your username, password and other information");
Break
}
}
Personal opinion: Adopt profile method, more convenient, because profile is strong type, can reduce the input of code through IntelliSense function. To take a custom data table, you need to enter a large number of SQL statements, but the query speed is faster, performance is relatively strong, because the Roles.getusersinrole () method can not read data paging, only a one-time read out all the data, and write SQL statements can be very convenient root page combination. With the increase in user volume, it is not recommended profile method.

   Third, the password question.

Personally think the password is a more headache problem. In actual development, we always need the admin group to have user password modification permissions. The modified password method provided by membership can only be modified when the password hint answer is already known. The admin group is not likely to know the user's password prompt answer at all. It's a little funny here. Is it a cultural difference between China and the West?

A list of personal insights into membership cryptography.

As we all know Machine.config and web.config, if there is a conflict, then Web.config priority.

By default, membership is encrypted using the SHA1 method, and then a mechanism is used to encrypt the passwordsalt again, and finally to form the password displayed in the database. It can be seen that with the MD5 encryption, Microsoft's password security is also painstaking.

Some friends do not like the default SHA1 encryption form, we only need to set the following code in the Web.config to overwrite the password set in the Machine.config is good:

<machinekey
validationkey= "Autogenerate,isolateapps"
decryptionkey= "Autogenerate,isolateapps"
decryption= "Auto"
validation= "Md5/sha1/clear"/>
which

Clear-The password is stored in plaintext. The user password can be compared directly with this value without further conversion required.

MD5-Stores the password using the Message Digest 5 (MD5) hash Digest. To validate the credentials, the user's password is hashed using the MD5 algorithm and the computed value is compared against the stored value. When this value is used, the plaintext password is never stored or compared. The performance of this algorithm is better than SHA1.

SHA1-Stores the password using the SHA1 Hash digest. To validate the credentials, the user's password is hashed using the SHA1 algorithm and the computed value is compared against the stored value. PlainText passwords are never stored. The algorithm can obtain higher security than the MD5 algorithm.

However, although MembershipUser provides the GetPassword method, this is only after the encryption form is set to clear, that is, the password in the database in the form of plaintext to get the password. The ChangePassword must provide an old password or a password prompt answer before it can be modified. The user management caused a lot of inconvenience. Found a lot of data without solution. By the way: Microsoft's membership mechanism originated from Csblog and made some modifications.

Csblog strategy: First encrypt the user's password (SHA1 or MD5), and then encrypt the encrypted password again according to the system's automatically generated key. However, I followed the Csblog method of encryption, the same form, the password is different, is currently in the play. We also welcome the joint discussion.

If PasswordSalt and password are fixed, then the user password must be certain. So one of the ways I'm currently taking this is to reset the user to a fixed password.

First get the PasswordSalt and password of the known user password, and then replace the corresponding user's PasswordSalt and password fields. At this point, the user's password has been restored to a known password.

Undeniably, membership to our development has created a great convenience, its convenient roles function, for us to conduct rights management when providing a very good solution. 2005 Many functions have evolved from Csblog this excellent open source project, interested parties can study csblog to further understand the membership operating mechanism. Limited to space, I will not repeat the description of the MSDN above. Just introduce the techniques not listed on MSDN with my experience in project development. ASP.net 2.0 provides an important security advantage for Web sites that use Forms authentication. By providing a repository of user profiles and support for roles, forms authentication can be achieved more widely by stepping out of the ASP.net's field of vision.

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.