Principle and application of ASP.net 2.0 membership

Source: Internet
Author: User
Tags abstract definition bool config modifiers prototype definition reflector static class
asp.net

   Summary: The membership component of ASP.net 2.0 provides a very easy-to-use set of interfaces for user management and user authentication by developers. This paper makes a simple analysis of its implementation principle, and describes how to use it correctly and how to extend it.

1, MembershipProvider abstract class

In many cases, we do not use this class directly when using membership. The MembershipProvider class defines abstract methods and abstract properties, that is, these methods and properties form the basic specification of the membership interface, and the functionality used within the. NET Framework to use membership is invoked through this type. Inheriting classes provide user-management functionality without context and have no effect on the membership framework itself by implementing these interfaces, the following is a MembershipProvider definition:

Public abstract class Membershipprovider:providerbase

... {

Events

public event Membershipvalidatepasswordeventhandler Validatingpassword;



Methods

protected MembershipProvider ();

public abstract bool ChangePassword (string username, string OldPassword, String newpassword);

public abstract bool Changepasswordquestionandanswer (string Username, string password, string newpasswordquestion, String newpasswordanswer);

Public abstract MembershipUser CreateUser (string Username, string password, string email, string passwordquestion, String Passwordanswer, bool isapproved, Object providerUserKey, out membershipcreatestatus status);

Protected virtual byte[] Decryptpassword (byte[] encodedpassword);

public abstract bool DeleteUser (string username, bool deleteallrelateddata);

Internal string Encodepassword (string pass, int passwordformat, string salt);

Protected virtual byte[] Encryptpassword (byte[] password);

Public abstract membershipusercollection FindUsersByEmail (string emailtomatch, int pageIndex, int pageSize, out int total Records);

Public abstract Membershipusercollection FindUsersByName (string usernametomatch, int pageIndex, int pageSize, out int tot Alrecords);

Internal string Generatesalt ();

Public abstract membershipusercollection getallusers (int pageIndex, int pageSize, out int totalrecords);

public abstract int getnumberofusersonline ();

Public abstract string GetPassword (string username, string answer);

Public abstract MembershipUser GetUser (object providerUserKey, bool userisonline);

Public abstract MembershipUser GetUser (string username, bool userisonline);

Internal MembershipUser GetUser (string username, bool userIsOnline, bool throwonerror);

Public abstract String Getusernamebyemail (string email);

protected virtual void Onvalidatingpassword (ValidatePasswordEventArgs e);

Public abstract string ResetPassword (string username, string answer);

Internal string Unencodepassword (string pass, int passwordformat);

public abstract bool Unlockuser (string userName);

public abstract void UpdateUser (MembershipUser user);

public abstract bool ValidateUser (string Username, string password);



Properties

Public abstract String ApplicationName ... {get; set;}

public abstract bool enablePasswordReset ... {get;}

public abstract bool enablePasswordRetrieval ... {get;}

public abstract int maxInvalidPasswordAttempts ... {get;}

public abstract int minRequiredNonalphanumericCharacters ... {get;}

public abstract int minRequiredPasswordLength ... {get;}

public abstract int passwordAttemptWindow ... {get;}

Public abstract Membershippasswordformat Passwordformat ... {get;}

Public abstract String passwordStrengthRegularExpression ... {get;}

public abstract bool requiresQuestionAndAnswer ... {get;}

public abstract bool requiresUniqueEmail ... {get;}



Fields

Private Membershipvalidatepasswordeventhandler _eventhandler;

Private Const int salt_size_in_bytes = 0x10;

}
Where modifiers are internal, several methods are used to encrypt, decrypt, and verify passwords. But the design here seems to have some problems, defining these methods as internal ranges seems a bit inappropriate, defining them in a base class to be able to be reused, but not in terms of effect, because the members of the internal are allowed to be used only in this assembly (normally, Other methods such as reflection are not included, which means that we cannot use these methods for our own extended membershipprovider. And from the current scope of application, these methods are only used in SqlMembershipProvider, so I think the method modifiers should be modified to protected.




2, membership static class

As mentioned above, we generally do not use the MembershipProvider abstraction directly, because it involves how to instantiate the real membership service class problem, and the problem of configuring and instantiating objects is generally a tricky problem, for beginners, It is not so easy to master. It was. NET Framework is to shield the complex relationships of this layer by membership (static Class). Membership (Static Class) In addition to the user screen read the configuration file, the initial object, and other basic work, there is an important role is to overload all MembershipProvider so there are APIs, even in order to make users more convenient to use, Overload these methods as static methods and provide a richer overload implementation based on the MembershipProvider base API for use by the consumer. This directly supports both the UI layer and the other projects, simply referencing the System.Web.Security namespace, without having to care for any details of the membership to provide us with all the conveniences. Here's a look at the prototype definition of membership (Static Class): (Using Lutz Roder's. NET Reflector to see all its implementations.) )

public static class Membership

... {

Events

public static event Membershipvalidatepasswordeventhandler Validatingpassword;



Methods

Static membership ();

public static MembershipUser CreateUser (string Username, string password);

public static MembershipUser CreateUser (string Username, string password, string email);

public static MembershipUser CreateUser (string Username, string password, string email, string passwordquestion, String pa Sswordanswer, bool isapproved, out membershipcreatestatus status);

public static MembershipUser CreateUser (string Username, string password, string email, string passwordquestion, String pa Sswordanswer, bool isapproved, Object providerUserKey, out membershipcreatestatus status);

public static bool DeleteUser (string username);

public static bool DeleteUser (string username, bool deleteallrelateddata);

public static Membershipusercollection FindUsersByEmail (string emailtomatch);

public static Membershipusercollection FindUsersByEmail (string emailtomatch, int pageIndex, int pageSize, out int totalre Cords);

public static Membershipusercollection FindUsersByName (string usernametomatch);

public static Membershipusercollection FindUsersByName (string usernametomatch, int pageIndex, int pageSize, out int total Records);

public static string Generatepassword (int length, int numberofnonalphanumericcharacters);

public static membershipusercollection getallusers ();

public static membershipusercollection getallusers (int pageIndex, int pageSize, out int totalrecords);

private static string Getcurrentusername ();

public static int Getnumberofusersonline ();

public static MembershipUser GetUser ();

public static MembershipUser GetUser (bool userisonline);

public static MembershipUser GetUser (object providerUserKey);

public static MembershipUser GetUser (string username);

public static MembershipUser GetUser (object providerUserKey, bool userisonline);

public static MembershipUser GetUser (string username, bool userisonline);

public static string Getusernamebyemail (string emailtomatch);

private static void Initialize ();

public static void UpdateUser (MembershipUser user);

public static bool ValidateUser (string Username, string password);



Properties

public static string ApplicationName ... {get; set;}

public static bool enablePasswordReset ... {get;}

public static bool enablePasswordRetrieval ... {get;}

public static string Hashalgorithmtype ... {get;}

Internal static bool Ishashalgorithmfrommembershipconfig ... {get;}

public static int maxinvalidpasswordattempts ... {get;}

public static int minRequiredNonalphanumericCharacters ... {get;}

public static int minRequiredPasswordLength ... {get;}

public static int passwordAttemptWindow ... {get;}

public static string passwordStrengthRegularExpression ... {get;}

public static MembershipProvider Provider ... {get;}

public static Membershipprovidercollection Providers ... {get;}

public static bool requiresQuestionAndAnswer ... {get;}

public static int Userisonlinetimewindow ... {get;}

Fields

private static char[] punctuations;

private static bool S_hashalgorithmfromconfig;

private static string S_hashalgorithmtype;

private static bool s_initialized;

private static Exception s_initializeexception;

private static object S_lock;

private static MembershipProvider S_provider;

private static membershipprovidercollection s_providers;

private static int S_userisonlinetimewindow;

}
Speaking of this, we have to doro two sentences. In the process of looking at membership (Static Class) Implementation code, you can find that each MEMBERSIP API overload is the last method to invoke the property provider, which is the type of the MembershipProvider type. It is only when you see here that you may understand the important role of MembershipProvider. There is also a providers property, which is to obtain all the membership provided service classes configured in Web.config. They are all static properties, but how are they instantiated? is by calling membership. Initialize () This method, in each invocation of these two properties, will call this method to determine whether the membership provided service classes have been initialized, if not to invoke the Configuration service class, read the configuration content, so that initialization. You may not find it difficult to understand why we use it so easily!

3. SqlMembershipProvider Introduction and Usage configuration

OK, through the above introduction should basically be able to understand the overall structure of membership it? (How not yet, maybe you haven't opened Lutz Roder ' s. NET Reflector to analyze its implementation code, or the role of abstract classes is not clear). In any case, our ultimate goal is to learn how to use it.

Before that, let me introduce you to the. NET Two MembershipProvider implementation classes provided in the framework: ActiveDirectoryMembershipProvider and SqlMembershipProvider (how do you know these two classes?) You can see all the inherited classes in the MembershipProvider derived types. The former is to provide user management under the Basic Activity directory (which I have not practiced), which is the most frequently used SQL Server based user management implementation.

To introduce how to use, in fact, the garden has already had this article (translation) in the ASP.net 2.0 use of membership), I do not have much to waste my breath. But here to tell you a most direct learning and reference to the use of the method. Locate and open machine.config on the system disk and locate the AspNetSqlMembershipProvider node:

<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= "passwordstrengthregularexpression=" "/>
</providers>
</membership>
See no, in fact this is a basic membership configuration, but is still less than a defaultprovider attribute of the specified, specify this property, you use the login control, user login authentication without using any code. Don't believe you can try. (For forms verification, do not here to do more introduction, you can refer to relevant information.) More about SqlMembershipProvider's properties can be described in MSDN.

4. How to customize MembershipProvider, existing other MembershipProvider resources

So, how do we go about customizing a membershipprovider? In fact, if you already understand the structure of membership I believe that it is not a very difficult thing for you, but considering that to write a complete membershipprovider still have a certain amount of work and difficulty. For us, more places may be extended to existing provider, such as SqlMembershipProvider. That's actually very simple, we just have to inherit from SqlMembershipProvider, (quietly tell you, The Initialize Method config parameter saves the provider the corresponding configuration section's property name and value, and then expands and overrides the desired method. When used, it is OK to change the value of type to your class name in the provider configuration section.

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.