1. 程式人生 > >ASP.NET MVC4 身份認證和授權

ASP.NET MVC4 身份認證和授權

        寒假準備對我們團隊開發的各個小系統進行整合和重寫,由於這些系統需求分析並不夠仔細,所以在後期縫縫補補,加上人員交替,使得程式碼結構凌亂不堪,讓我這個有程式碼潔癖的人難受的要死,所以打算重新梳理,由於我們團隊主攻asp.net mvc開發,(我對asp.net mvc的學習和使用是從2開始,到現在我們專案基本用的是3),重新寫一遍系統,當然要有點新的嘗試,雖然現在asp.net mvc5已釋出,但感覺使用asp.net mvc4開發的人都不多,何況是5,而且出現問題估計網上搜索解決,也比較麻煩,所以還是一步一步來,用mvc4吧:

環境:

1、資料庫:SQL Server 2008

2、開發:Visual Studio 2013/Framework4.0

開始構建基礎框架
在VS2013中新建一個mvc4專案,新增加了些和以前不同的資料夾,刪除掉自己不需要的,然後把以前專案的靜態頁面整合入專案,按結構把母板頁,區域性頁設計完成,對照了些以前系統的各個模組,覺得登入,註冊這塊還是自己來完成搭建較好,看了下VS2013的mvc4專案的Account的東西,新增了SimpleMembership、WebMatrix等的一些東西,以前沒接觸過,看來mvc3到mvc4還是有點變化的(除了有打包功能等)
微軟提供一套身份認證與授權的東西,但都是用微軟自己的資料庫欄位等等,我們這種小作坊開發有點用不上,想用自己的資料庫和欄位結構,往往我們一般是將登入成功後的資訊按情況存入session或是cookie中。
       但我程式碼潔癖的性格不能容忍這樣的寫法,我一定要用微軟的身份認證與授權的寫法規範,來實現。

       之前經過網上查資料,我們在asp.net mvc3專案中Account的寫法如下:
       所有的都在AccountModel中修改:
       Services區域:在對IMembershipService的介面例項化方法時:重新申明自己定義的MembershipProvider(對MembershipProvider的方法的重寫),結束。

       但asp.net mvc4預設的AccountModel寫法變了,新增了SimpleMembership,WebMatrix等,廢話少說,經過MSDN查詢資料和Stack Overflow看老外的介紹,再結合反編譯WebMatrix的dll檔案,大概看出:其實webMatrix就是對mvc3的account的封裝,然後SimpleMembership就是自定義出SimpleMembership的資料庫和自定義欄位,那對於我們來說SimpleMembership是不需要的,我們要構建自己的MyMembership,然後該怎麼做呢?
       首先:webconfig中,禁用SimpleMembership
      <appSettings>
         <add key="enableSimpleMembership" value="false" />


      </appSettings>
      然後:告訴WebMatrix,我們要用的是哪個Membership?,即我們自己的MyMembership:Membership
      <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    <membership defaultProvider="MyMembershipProvider">
      <providers>
        <clear />
        <add name="MyMembershipProvider" type="定義
MyMembershipProvider的名稱空間.MyMembershipProvider" />
      </providers>
    </membership>

     最後:新建類,實現ExtendedMembershipProvider的方法
    public class MyMembershipProvider : ExtendedMembershipProvider(引用using WebMatrix.WebData;)
    {
        public override bool ConfirmAccount(string accountConfirmationToken)
        {
            throw new NotImplementedException();
        }

        public override bool ConfirmAccount(string userName, string accountConfirmationToken)
        {
            throw new NotImplementedException();
        }

        public override string CreateAccount(string userName, string password, bool requireConfirmationToken)
        {
            throw new NotImplementedException();
        }

        public override string CreateUserAndAccount(string userName, string password, bool requireConfirmation, IDictionary<string, object> values)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteAccount(string userName)
        {
            throw new NotImplementedException();
        }

        public override string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow)
        {
            throw new NotImplementedException();
        }

        public override ICollection<OAuthAccountData> GetAccountsForUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override DateTime GetCreateDate(string userName)
        {
            throw new NotImplementedException();
        }

        public override DateTime GetLastPasswordFailureDate(string userName)
        {
            throw new NotImplementedException();
        }

        public override DateTime GetPasswordChangedDate(string userName)
        {
            throw new NotImplementedException();
        }

        public override int GetPasswordFailuresSinceLastSuccess(string userName)
        {
            throw new NotImplementedException();
        }

        public override int GetUserIdFromPasswordResetToken(string token)
        {
            throw new NotImplementedException();
        }

        public override bool IsConfirmed(string userName)
        {
            throw new NotImplementedException();
        }

        public override bool ResetPasswordWithToken(string token, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { throw new NotImplementedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new NotImplementedException(); }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            throw new NotImplementedException();
        }
    }