zoukankan      html  css  js  c++  java
  • 重写MembershipProvider实现自己的身份验证

    众所周知
    .Net 2.0推出来以后一些新的控件给我们的开发带来极大的便利
    在Form验证上更是如此
    内置的Login控件可以让我们不写一行代码实现基本的Form验证
    这样的验证默认是基于AspNetSqlProvider验证的
    利用的数据库是aspnet_db库
    但有时我们需要用自己的用户库,又想用login控件那该怎么办呢?
    我们可以重写MembershipProvider类
    该类是一个抽象类,我们可以通过重写来实现我们所需要的结果

    具体关于该类的属性和方法可参阅MSDN文档,这里就不浪费口水了
    先看我写的这个

    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    /// <summary>
    /// SqlMembershipProvider 的摘要说明
    /// </summary>
    public class SqlMembershipProvider:MembershipProvider
    {
        private string connStr = ConfigurationManager.ConnectionStrings["DefaultConnectionstrings"].ConnectionString;

        private bool _requiresQuestionAndAnswer;
        private int _minRequiredPasswordLength;
    public SqlMembershipProvider()
    {
    //
    // TODO: 在此处添加构造函数逻辑
    //
    }
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
           
            if (config["requiresQuestionAndAnswer"].ToLower() == "true")
                _requiresQuestionAndAnswer = true;
            else
                _requiresQuestionAndAnswer = false;
            int.TryParse(config["minPasswordLength"], out _minRequiredPasswordLength);
            base.Initialize(name, config);
        }
        public override string ApplicationName
        {
            get
            {
                throw new Exception("The method or operation is not implemented.");
            }
            set
            {
                throw new Exception("The method or operation is not implemented.");
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override bool EnablePasswordReset
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override string GetPassword(string username, string answer)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public override int MinRequiredPasswordLength
        {
            get { return _minRequiredPasswordLength; }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return _requiresQuestionAndAnswer; }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override bool UnlockUser(string userName)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new Exception("The method or operation is not implemented.");
        }

       //验证用户
        public override bool ValidateUser(string username, string password)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                SqlCommand comm = new SqlCommand();
                comm.CommandText = "select * from registers where name=@name and pwd=@pwd";
                comm.Parameters.Add("@name", SqlDbType.NVarChar, 50).Value = username;
                comm.Parameters.Add("@pwd", SqlDbType.VarChar, 100).Value = password;
                comm.Connection = conn;
                conn.Open();
                SqlDataReader dr = comm.ExecuteReader(CommandBehavior.CloseConnection);
                if (dr.HasRows)
                    return true;
                return false;
            }
        }
    }


    还有一些方法大家就参阅文档了
    最后要做的就是修改你的web.config文件
     <membership defaultProvider="SqlMembershipProvider">
          <providers >
            <add name="SqlMembershipProvider" type="SqlMembershipProvider" requiresQuestionAndAnswer="true" minPasswordLength="20"/>
          </providers>
        </membership>
    这样就可以用Login控件来实现自己的身份验证了,同样你也可以重写RoleProvider类来实现自己的基于角色的身份验证
    因为爱上你,我才懂得珍惜,每一天日记,都写满了甜蜜
    因为想念你,我每天都可以,对着镜子说我多爱你,有多想见到你。
  • 相关阅读:
    asp.net url传参中使用javascript过滤中文乱码
    Javascript 操作select控件大全(新增、修改、删除、选中、清空、判断存在等)【转】
    element.firstChild
    NHibernate使用Criteria分页显示并返回记录总数 【转】
    动态生成select选项全接触Javascript技术【转】
    struts中ApplicationResources.properties支持中文
    博客园博客美化方法大全[附源码]
    fileinput模块
    python学习
    遗忘的果实
  • 原文地址:https://www.cnblogs.com/jackzhang/p/569273.html
Copyright © 2011-2022 走看看