Community Server专题八:MemberRole之Membership [转]

MemberRole是一个在asp.net  1 .1下实现用户管理、角色管理、用户特性信息存储(profile)等的一个组件,该组件被ASP.NET  2.0  Beta 2所采用,也就是ASP.NET  2.0  Beta 2中所说的Membership and Roles。如果你在asp.net  1 .1下采用了MemberRole,那么你的web程序将会很容易的过渡到asp.net  2.0 ,另外多个采取MemberRole进行用户管理的web程序需要整合时也非常容易。我将分4个专题来分析MemberRole,探索一下MemberRole到底是如何工作的,无论对CS的构架还是对了解asp.net  2 .0都是非常有帮助的。
None.gif
None.gifCS中,运用该组件的4个部分:membership、roleManager、profile、anonymousIdentification的运用(整个MemberRole也这四部分功能)。
None.gif
None.gif在分析前,准备需要一个工具:Reflector.exe,没有的朋友google一下,下载它。
None.gif
None.gif本次专题分析membership,先看一下CS中Membership的配置文件(Web.Config中):
None.gif
None.gif
< membership userIsOnlineTimeWindow = " 15 "   >
None.gif
None.gif              
< providers >
None.gif
None.gif                   
< add 
None.gif
None.gif                       name
= " CommunityServerSqlProvider "               
None.gif
None.gif                       type
= " Openlab.AutoRegister.CSAutoBlogGalleryMembershipProvider, Openlab.CSAddOns "
None.gif
None.gif                       connectionStringName
= " SiteSqlServer "
None.gif
None.gif                       enablePasswordRetrieval
= " false "
None.gif
None.gif                       enablePasswordReset
= " true "
None.gif
None.gif                       requiresQuestionAndAnswer
= " false "
None.gif
None.gif                       requiresUniqueEmail
= " true "
None.gif
None.gif                       passwordFormat
= " Hashed "
None.gif
None.gif                       applicationName
= " dev "
None.gif
None.gif                       description
= " Stores and retrieves membership data from the local Microsoft SQL Server database "
None.gif
None.gif                       autoCreateBlog
= " false "
None.gif
None.gif                       defaultBlogGroupID
= " 3 "
None.gif
None.gif                       autoCreateGallery
= " false "
None.gif
None.gif                       defaultGalleryGroupID
= " 2 "
None.gif
None.gif                       maxInvalidPasswordAttempts 
=   " 999 "
None.gif
None.gif                       passwordAttemptWindow 
=   " 999 "
None.gif
None.gif                       minRequiredPasswordLength 
=   " 4 "
None.gif
None.gif                       minRequiredNonalphanumericCharacters 
=   " 0 "
None.gif
None.gif                   
/>
None.gif
None.gif              
</ providers >
None.gif
None.gif
</ membership >
None.gif
None.gifuserIsOnlineTimeWindow:这是一个数值,用来计算在线用户的数量,例如:
15 ,就表示如果用户在15分钟后不活动(发出Http请求)CS系统将视该用户不在线。
None.gif
None.gifName:名称
None.gif
None.giftype:类的名字空间与所在的程序集合
None.gif
None.gifconnectionStringName:数据库连接字符串节点的key。通过这个key就可以找到连接数据库的用户名与密码
None.gif
None.gifenablePasswordRetrieval:是否打开取回秘密功能
None.gif
None.gifenablePasswordReset:是否打开秘密重新设功能
None.gif
None.gifrequiresQuestionAndAnswer:注册时是否需要填写Question与Answer
None.gif
None.gifrequiresUniqueEmail:注册时是否Email唯一
None.gif
None.gifpasswordFormat:密码的加密格式
None.gif
None.gifapplicationName:使用该membership应用程序的名称
None.gif
None.gifdescription:描述信息
None.gif
None.gif 
None.gif
None.gif以下4个参数是CCS中添加的,目的是给注册用户自动开通相册和博客
None.gif
None.gifautoCreateBlog:是否当用户注册时自动为该用户建立一个Blog
None.gif
None.gifdefaultBlogGroupID:默认的建立blog的分组ID
None.gif
None.gifautoCreateGallery:是否当用户注册时自动为该用户建立一个相册
None.gif
None.gifdefaultGalleryGroupID:默认的建立相册的分组ID
None.gif
None.gif 
None.gif
None.gif用Reflector.exe打开MemberRole.dll,你可以看到以下的内容:
None.gif
None.gif
None.gif再打开Microsoft.ScalableHosting.Configuration节点
None.gif
None.gif
None.gif这次我们只关注两个类MembershipConfig、MembershipConfigHandler。MembershipConfigHandler实现了IConfigurationSectionHandler接口。也就是说,CS启动后如果调用ConfigurationSettings.GetConfig(
" memberrolesprototype/membership " ),系统将会自动的调用MembershipConfigHandler中的Create方法把web.config中memberrolesprototype / membership的配置内容读入进行处理。先看以下Create做了些什么:
None.gif
None.gif
public   virtual   object  Create( object  parent,  object  configContextObj, XmlNode section)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif      MembershipConfig config1 
= new MembershipConfig(parent as MembershipConfig);
InBlock.gif      
int num1 = -1;
InBlock.gif      ConfigUtils.GetAndRemovePositiveIntegerAttribute(section, 
"userIsOnlineTimeWindow"ref num1);
InBlock.gif      
if (num1 > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif            config1.UserIsOnlineTimeWindow 
= num1;
ExpandedSubBlockEnd.gif      }

InBlock.gif      
string text1 = null;
InBlock.gif      ConfigUtils.GetAndRemoveStringAttribute(section, 
"hashAlgorithm"ref text1);
InBlock.gif      
if ((text1 != null&& (text1.Length > 0))
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif            config1.HashAlgorithmType 
= text1;
ExpandedSubBlockEnd.gif      }

InBlock.gif      ConfigUtils.CheckForUnrecognizedAttributes(section);
InBlock.gif      MembershipProvider provider1 
= null;
InBlock.gif      
foreach (XmlNode node1 in section.ChildNodes)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif            
if (node1.NodeType != XmlNodeType.Element)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                  
continue;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
if (node1.Name != "providers")
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                  
throw new ConfigurationException("Unrecognized tag: " + node1.Name, node1);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
foreach (XmlNode node2 in node1.ChildNodes)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                  
if (node2.NodeType == XmlNodeType.Element)
ExpandedSubBlockStart.gifContractedSubBlock.gif                  
dot.gif{
InBlock.gif                        
if (node2.Name != "add")
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                              
throw new ConfigurationException("Unrecognized tag: " + node2.Name, node2);
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        
if (provider1 != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                              
throw new ConfigurationException("Only one provider can be configured", node2);
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        
string text2 = null;
InBlock.gif                        
string text3 = null;
InBlock.gif                        ConfigUtils.GetAndRemoveRequiredNonEmptyStringAttribute(node2, 
"name"ref text2);
InBlock.gif                        ConfigUtils.GetAndRemoveRequiredNonEmptyStringAttribute(node2, 
"type"ref text3);
InBlock.gif                        NameValueCollection collection1 
= new NameValueCollection();
InBlock.gif                        
foreach (XmlAttribute attribute1 in node2.Attributes)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                              
if ((attribute1.Name != null&& (attribute1.Name.Length > 0))
ExpandedSubBlockStart.gifContractedSubBlock.gif                              
dot.gif{
InBlock.gif                                    collection1.Add(attribute1.Name, attribute1.Value);
ExpandedSubBlockEnd.gif                              }

ExpandedSubBlockEnd.gif                        }

InBlock.gif                        provider1 
= (MembershipProvider) Activator.CreateInstance(Type.GetType(text3, true));
InBlock.gif                        provider1.Initialize(text2, collection1);
InBlock.gif                        config1.Provider 
= provider1;
ExpandedSubBlockEnd.gif                  }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif      }

InBlock.gif      
return config1;
ExpandedBlockEnd.gif}

None.gif
None.gif 
None.gif
None.gif代码有点长,其实这里就是把web.config下面membership节点的配置信息读入,进行初始化,然后通过GetType与Activator.CreateInstance方法反射后实例化一个MembershipProvider。
None.gif
None.gifMembershipProvider又是什么,继续看看:
None.gif
None.gif
public   abstract   class  MembershipProvider : ProviderBase
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif      
// Events
InBlock.gif
      public event MembershipValidatePasswordEventHandler ValidatingPassword;
InBlock.gif 
InBlock.gif      
// Methods
InBlock.gif
      protected MembershipProvider();
InBlock.gif      
public abstract bool ChangePassword(string username, string oldPassword, string newPassword);
InBlock.gif      
public abstract bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer);
InBlock.gif      
public abstract MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status);
InBlock.gif      
protected virtual byte[] DecryptPassword(byte[] encodedPassword);
InBlock.gif      
public abstract bool DeleteUser(string username, bool deleteAllRelatedData);
InBlock.gif      
internal string EncodePassword(string pass, int passwordFormat, string salt);
InBlock.gif      
protected virtual byte[] EncryptPassword(byte[] password);
InBlock.gif      
public abstract MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords);
InBlock.gif      
public abstract MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords);
InBlock.gif      
internal string GenerateSalt();
InBlock.gif      
public abstract MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords);
InBlock.gif      
public abstract int GetNumberOfUsersOnline();
InBlock.gif      
public abstract string GetPassword(string username, string answer);
InBlock.gif      
public abstract MembershipUser GetUser(object providerUserKey, bool userIsOnline);
InBlock.gif      
public abstract MembershipUser GetUser(string username, bool userIsOnline);
InBlock.gif      
public abstract string GetUserNameByEmail(string email);
InBlock.gif      
protected virtual void OnValidatingPassword(ValidatePasswordEventArgs e);
InBlock.gif      
public abstract string ResetPassword(string username, string answer);
InBlock.gif      
internal string UnEncodePassword(string pass, int passwordFormat);
InBlock.gif      
public abstract bool UnlockUser(string userName);
InBlock.gif      
public abstract void UpdateUser(MembershipUser user);
InBlock.gif      
public abstract bool ValidateUser(string username, string password);
InBlock.gif 
InBlock.gif      
// Properties
ExpandedSubBlockStart.gifContractedSubBlock.gif
      public abstract string ApplicationName dot.gifgetset; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract bool EnablePasswordReset dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract bool EnablePasswordRetrieval dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract int MaxInvalidPasswordAttempts dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract int MinRequiredNonAlphanumericCharacters dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract int MinRequiredPasswordLength dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract int PasswordAttemptWindow dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract MembershipPasswordFormat PasswordFormat dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract string PasswordStrengthRegularExpression dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract bool RequiresQuestionAndAnswer dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract bool RequiresUniqueEmail dot.gifget; }
InBlock.gif 
InBlock.gif      
// Fields
InBlock.gif
      private MembershipValidatePasswordEventHandler _EventHandler;
InBlock.gif      
private const int SALT_SIZE_IN_BYTES = 0x10;
ExpandedBlockEnd.gif}

None.gif原来MembershipProvider是实现继承了ProviderBase的一个类,其实ProviderBase并没有什么,看看代码
None.gif
None.gif
public   abstract   class  ProviderBase
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif      
// Methods
InBlock.gif
      protected ProviderBase();
InBlock.gif      
public virtual void Initialize(string name, NameValueCollection config);
InBlock.gif 
InBlock.gif      
// Properties
ExpandedSubBlockStart.gifContractedSubBlock.gif
      public virtual string Description dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public virtual string Name dot.gifget; }
InBlock.gif 
InBlock.gif      
// Fields
InBlock.gif
      private string _Description;
InBlock.gif      
private bool _Initialized;
InBlock.gif      
private string _name;
ExpandedBlockEnd.gif}

None.gif
None.gifProviderBase仅仅只是保护了两个虚属性的类,设置这个类只是一种设计模式,没有特别的用途。我们把重点集中到MembershipProvider上,其实MembershipProvider类是Provider构架的一种体现形式,Provider构架常常用到对数据库的访问上,实现多数据库,同时也可以很好的隔离数据层与业务层的代码有利于协作开发。具体实现是这样的,先把要操作数据库的方法抽象出来,单独的放入一个abstract类,例如:MembershipProvider,然后通过继承,把这些抽象的方法全部的实现出来,例如:SqlMembershipProvider。这样有什么好处呢?对于三层构架的web应用程序来说,中间的业务逻辑层调用操作数据库的方法是从MembershipProvider,对于该层来说它并不关心该抽象层是如何被继承后实现抽象方法的。它只关心抽象层中是否有它想要的方法。如果能理解到这里,嘿嘿,我们的机会就来了,因为这隔离了具体的数据库操作实现,更进一步说就是隔离了使用何种数据库。再从团队协作考虑,假设你的MembershipProvider定义的完善后,继承MembershipProvider实现SQL Server操作的SqlMembershipProvider类中的方法无论怎么改变,都不会影响其它人员在业务逻辑层的开发。听起来这种方式好像很美,但是要实现这样的功能还需要一个关键的技术,那就是反射,所以我们看到在配置的字段里有这样的字节:。
None.gif
None.giftype
= " Openlab.AutoRegister.CSAutoBlogGalleryMembershipProvider, Openlab.CSAddOns "
None.gif
None.gif这就是为了通过反射找到MembershipProvider具体方法实现的类而做的准备。
None.gif
None.gif注:由于分析的代码来源于宝玉的CCS,在CCS中为了实现注册后能自动开通博客与相册又继承了SqlMembershipProvider类,重写了几个方法(关键是其中的Initialize与CreateUser方法)。
None.gif
None.gif只要你继承MembershipProvider类,对其中的抽象方法进行实现,无论你是实现对Access的操作,还是其它数据库,都是没有问题的。在asp.net 
2.0  beta2中的Membership已经提供access与sql server两种数据库操作实现。不过MemberRole.dll程序集中只实现了SqlMembershipProvider,也就是对SQL Server的操作。
None.gif
None.gif其实Membership是一个没有表示层的运用组件,它包含了逻辑层与数据操作层,数据层我在这个专题中就不多做解释,他的实现是在SqlMembershipProvider类中,你可以通过Reflector.exe慢慢研究。上面的文字说过,实现Provider模式后业务逻辑层对数据层具体实现就不关心了,在MemberRole.dll中的Membership,它把所有的这些逻辑用一个类包装起来,那就是Membership类:
None.gif
None.gif
None.gif对于引用MemberRole.dll实现Membership功能的web app(DNN,CS就是典型)来说,只要做合适的配置之后就可以直接使用了。
None.gif
None.gif例如,要建立一个用户只要调用Membership.CreateUser的静态方法,就可以完成(Membership会根据内部的方法和具体的数据库操作,把用户信息写入数据库)。
None.gif
None.gif对于使用Membership来开发web app的程序员来说,完全可以不必要了解这些细节,asp 
2.0  beta2就没有提供这样的机会,MS只要求你会用就可以了,不过很庆幸的是CS给我们提供了这样的一个机会,了解这些操作的实质(包括URL Rewrite等功能也是一样,这些功能都可以在asp  2.0  beta2中直接使用,而不要构架如何代码)。
None.gif
None.gif这个专题只是大致的讲解了Membership,下一个专题,我们将更深入的去看看Membership的数据层的操作实现以及数据库表的设计(包括存储过程)。

转载于:https://www.cnblogs.com/guodapeng/archive/2007/12/21/1009078.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值