public AuthenticationResult Authenticate(string identity, string password, string @namespace = null) { if(string.IsNullOrWhiteSpace(identity)) throw new ArgumentNullException("identity"); byte[] storedPassword; byte[] storedPasswordSalt; bool isApproved, isSuspended; //获取当前用户的密码及密码向量 var userId = this.GetPassword(identity, @namespace, out storedPassword, out storedPasswordSalt, out isApproved, out isSuspended); //如果帐户不存在,则抛出异常 if(userId == null) { //激发“Authenticated”事件 this.OnAuthenticated(new AuthenticatedEventArgs(identity, @namespace, false)); //指定的用户名如果不存在则抛出验证异常 throw new AuthenticationException(AuthenticationReason.InvalidIdentity); } //如果帐户尚未审核批准,则抛出异常 if(!isApproved) { //激发“Authenticated”事件 this.OnAuthenticated(new AuthenticatedEventArgs(identity, @namespace, false)); //密码校验失败则抛出验证异常 throw new AuthenticationException(AuthenticationReason.AccountUnapproved); } //如果帐户已被禁用,则抛出异常 if(isSuspended) { //激发“Authenticated”事件 this.OnAuthenticated(new AuthenticatedEventArgs(identity, @namespace, false)); //密码校验失败则抛出验证异常 throw new AuthenticationException(AuthenticationReason.AccountSuspended); } //如果验证失败,则抛出异常 if(!PasswordUtility.VerifyPassword(password, storedPassword, storedPasswordSalt, "SHA1")) { //激发“Authenticated”事件 this.OnAuthenticated(new AuthenticatedEventArgs(identity, @namespace, false)); //密码校验失败则抛出验证异常 throw new AuthenticationException(AuthenticationReason.InvalidPassword); } //获取指定用户编号对应的用户对象 var user = MembershipHelper.GetUser(this.EnsureService<IDataAccess>(), userId.Value); //创建“Authenticated”事件参数 var eventArgs = new AuthenticatedEventArgs(identity, @namespace, true, user); //激发“Authenticated”事件 this.OnAuthenticated(eventArgs); //返回成功的验证结果 return new AuthenticationResult(eventArgs.User ?? user, (eventArgs.HasExtendedProperties ? eventArgs.ExtendedProperties : null)); }
protected virtual void OnAuthenticated(AuthenticatedEventArgs args) { var handler = this.Authenticated; if(handler != null) handler(this, args); }