ASP.NET 成員資格和角色管理

 成員資格和角色管理

目標

成員資格管理

成員角色管理

成員資格管理

在Web應用程序中有關成員驗證、管理等內容基本沒有太大區別。可以考慮將這些相對固定的內容抽象並形成獨立的模型以方便我們的開發。ASP.NET解決了這個方案,提供了成員資格管理器功能。核心的利用內置的成員庫表(SQL Server)、成員資格管理API(Membership、MembershipUser等)、成員資格提供程序(SqlMembershipProvider等),實現模塊化和自動化的成員資格管理模式。

成員資格簡介

ASP.NET成員資格支持下列功能:

(1)創建新用戶和密碼。

(2)將成員資格信息(用戶名、密碼和支持數據)存儲在Microsoft SQL Server、Active Directory或其他數據存儲區。

(3)對訪問站點的用戶進行身份驗證。可以以編輯方式驗證用戶,也可以使用ASP.NET登錄控件創建一個只需要很少代碼或無代碼的完整身份驗證系統。

(4)管理密碼,包括創建、更改和重置密碼。根據用戶選擇的成員資格選項不同,成員資格系統還可以提供一個使用用戶提供的問題和答案的自動密碼重置系統。

(5)公開經過身份驗證的用戶的唯一標識,用戶可以在自己的應用程序中使用該標識,也可以將該標誌與ASP.NET個性化設置和角色管理(授權)系統集成。

(6)指定自定義成員資格提供程序,使用戶可以改爲自己的代碼管理成員資格及自定義數據存儲區中維護成員資格數據。

Membership類

Membership類用於驗證用戶憑據並管理用戶設置。Membership類可以獨自使用,或者與FormsAuthentication類一起使用,以便創建一個完整的站點用戶身份驗證系統。

Membership類具有以下幾個主要功能:

(1)創建和管理用戶

(2)將成員資格信息存儲在SQL Server或其他數據存儲區中。

(3)對訪問站點的用戶進行身份驗證。可以使用編輯方式對用戶進行身份驗證,也可以使用登錄控件創建一個只需很少代碼或無需代碼的完整身份驗證系統。

(4)管理密碼,包括創建、更改、檢索和重置密碼等。可以選擇配置成員資格管理功能,以要求一個密碼提示問題及其答案來對忘記密碼的用戶的密碼進行重置。

Membership類的默認提供程序將用戶信息以預定格式儲存到一個SQL Server數據庫ASPNETDB中,如果需要使用一個定製的數據庫,則可以創建自己提供的程序。

Membership類的屬性

Membership類的方法


建立成員資格支持

要創建一個基於成員資格API的身份驗證層,首先選擇成員資格提供程序和建立數據存儲。

(1)點擊“開始”選擇“程序”,選擇“Microsoft Visual Studio 2010”選擇“Visual Studio Tools”最後點擊“Visual Studio 命令提示(2010)”,彈出“Visual Studio 命令提示(2010)”對話框,在對話框中輸入“aspnet_regsql”點擊回車。

(2)彈出“ASP.NET SQL Server安裝嚮導”,點擊“下一步”,彈出“選擇安裝選項”,選擇“爲應用程序服務配置SQL Server(0)”,點擊“下一步”。

(3)彈出“選擇服務器和數據庫”,服務器填寫“.”,數據庫選擇“默認”,點擊“下一步”,彈出“請確定您的設置”,點擊“下一步”。

(4)彈出“數據庫已被創建或修改”,點擊“完成”,返回“Visual Studio 命令提示(2010)”提示符對話框。

(5)打開“SQL Server Management Studio”軟件,點擊“數據庫”右鍵選擇“刷新”。

(6)打開“Microsoft Visual Studio 2010”,點擊“新建”選擇“項目”,彈出“新建項目”模版,在模版中選擇“Web”——“ASP.NET Web應用程序”,點擊“確定”


(7)在“WebApplocation”右鍵點擊“添加”——“新建項”,彈出“添加新項”模版,選擇“Web”——“Web窗體”,更改“名稱”點擊“添加”。

(8)之後就是添加一系列代碼:(以下以圖片顯示)點擊“開始”選擇“程序”,找到“Microsoft Visual Studio 2010”選擇“Microsoft Visual Studio 2010 文檔”,彈出“Microsoft Help查看器”。


之後在添加的新頁面中複製圖中紫色的代碼點擊進入找到的代碼形式爲:

  1. <form id="form1" runat="server">  
  2.    <h3>  
  3.        Create New User</h3>  
  4.    <asp:Label ID="Msg" ForeColor="maroon" runat="server" /><br />  
  5.    <table cellpadding="3" border="0">  
  6.        <tr>  
  7.            <td>  
  8.                Username:  
  9.            </td>  
  10.            <td>  
  11.                <asp:TextBox ID="UsernameTextbox" runat="server" />  
  12.            </td>  
  13.            <td>  
  14.                <asp:RequiredFieldValidator ID="UsernameRequiredValidator" runat="server" ControlToValidate="UserNameTextbox"  
  15.                    ForeColor="red" Display="Static" ErrorMessage="Required" />  
  16.            </td>  
  17.        </tr>  
  18.        <tr>  
  19.            <td>  
  20.                Password:  
  21.            </td>  
  22.            <td>  
  23.                <asp:TextBox ID="PasswordTextbox" runat="server" TextMode="Password" />  
  24.            </td>  
  25.            <td>  
  26.                <asp:RequiredFieldValidator ID="PasswordRequiredValidator" runat="server" ControlToValidate="PasswordTextbox"  
  27.                    ForeColor="red" Display="Static" ErrorMessage="Required" />  
  28.            </td>  
  29.        </tr>  
  30.        <tr>  
  31.            <td>  
  32.                Confirm Password:  
  33.            </td>  
  34.            <td>  
  35.                <asp:TextBox ID="PasswordConfirmTextbox" runat="server" TextMode="Password" />  
  36.            </td>  
  37.            <td>  
  38.                <asp:RequiredFieldValidator ID="PasswordConfirmRequiredValidator" runat="server"  
  39.                    ControlToValidate="PasswordConfirmTextbox" ForeColor="red" Display="Static" ErrorMessage="Required" />  
  40.                <asp:CompareValidator ID="PasswordConfirmCompareValidator" runat="server" ControlToValidate="PasswordConfirmTextbox"  
  41.                    ForeColor="red" Display="Static" ControlToCompare="PasswordTextBox" ErrorMessage="Confirm password must match password." />  
  42.            </td>  
  43.        </tr>  
  44.        <tr>  
  45.            <td>  
  46.                Email Address:  
  47.            </td>  
  48.            <td>  
  49.                <asp:TextBox ID="EmailTextbox" runat="server" />  
  50.            </td>  
  51.            <td>  
  52.                <asp:RequiredFieldValidator ID="EmailRequiredValidator" runat="server" ControlToValidate="EmailTextbox"  
  53.                    ForeColor="red" Display="Static" ErrorMessage="Required" />  
  54.            </td>  
  55.        </tr>  
  56.        <% if (Membership.RequiresQuestionAndAnswer)  
  57.           { %>  
  58.        <tr>  
  59.            <td>  
  60.                Password Question:  
  61.            </td>  
  62.            <td>  
  63.                <asp:TextBox ID="PasswordQuestionTextbox" runat="server" />  
  64.            </td>  
  65.            <td>  
  66.                <asp:RequiredFieldValidator ID="PasswordQuestionRequiredValidator" runat="server"  
  67.                    ControlToValidate="PasswordQuestionTextbox" ForeColor="red" Display="Static"  
  68.                    ErrorMessage="Required" />  
  69.            </td>  
  70.        </tr>  
  71.        <tr>  
  72.            <td>  
  73.                Password Answer:  
  74.            </td>  
  75.            <td>  
  76.                <asp:TextBox ID="PasswordAnswerTextbox" runat="server" />  
  77.            </td>  
  78.            <td>  
  79.                <asp:RequiredFieldValidator ID="PasswordAnswerRequiredValidator" runat="server" ControlToValidate="PasswordAnswerTextbox"  
  80.                    ForeColor="red" Display="Static" ErrorMessage="Required" />  
  81.            </td>  
  82.        </tr>  
  83.        <% } %>  
  84.        <tr>  
  85.            <td>  
  86.            </td>  
  87.            <td>  
  88.                <asp:Button ID="CreateUserButton" Text="Create User" OnClick="CreateUser_OnClick"  
  89.                    runat="server" />  
  90.            </td>  
  91.        </tr>  
  92.    </table>  
  93.    </form>  
 <form id="form1" runat="server">
    <h3>
        Create New User</h3>
    <asp:Label ID="Msg" ForeColor="maroon" runat="server" /><br />
    <table cellpadding="3" border="0">
        <tr>
            <td>
                Username:
            </td>
            <td>
                <asp:TextBox ID="UsernameTextbox" runat="server" />
            </td>
            <td>
                <asp:RequiredFieldValidator ID="UsernameRequiredValidator" runat="server" ControlToValidate="UserNameTextbox"
                    ForeColor="red" Display="Static" ErrorMessage="Required" />
            </td>
        </tr>
        <tr>
            <td>
                Password:
            </td>
            <td>
                <asp:TextBox ID="PasswordTextbox" runat="server" TextMode="Password" />
            </td>
            <td>
                <asp:RequiredFieldValidator ID="PasswordRequiredValidator" runat="server" ControlToValidate="PasswordTextbox"
                    ForeColor="red" Display="Static" ErrorMessage="Required" />
            </td>
        </tr>
        <tr>
            <td>
                Confirm Password:
            </td>
            <td>
                <asp:TextBox ID="PasswordConfirmTextbox" runat="server" TextMode="Password" />
            </td>
            <td>
                <asp:RequiredFieldValidator ID="PasswordConfirmRequiredValidator" runat="server"
                    ControlToValidate="PasswordConfirmTextbox" ForeColor="red" Display="Static" ErrorMessage="Required" />
                <asp:CompareValidator ID="PasswordConfirmCompareValidator" runat="server" ControlToValidate="PasswordConfirmTextbox"
                    ForeColor="red" Display="Static" ControlToCompare="PasswordTextBox" ErrorMessage="Confirm password must match password." />
            </td>
        </tr>
        <tr>
            <td>
                Email Address:
            </td>
            <td>
                <asp:TextBox ID="EmailTextbox" runat="server" />
            </td>
            <td>
                <asp:RequiredFieldValidator ID="EmailRequiredValidator" runat="server" ControlToValidate="EmailTextbox"
                    ForeColor="red" Display="Static" ErrorMessage="Required" />
            </td>
        </tr>
        <% if (Membership.RequiresQuestionAndAnswer)
           { %>
        <tr>
            <td>
                Password Question:
            </td>
            <td>
                <asp:TextBox ID="PasswordQuestionTextbox" runat="server" />
            </td>
            <td>
                <asp:RequiredFieldValidator ID="PasswordQuestionRequiredValidator" runat="server"
                    ControlToValidate="PasswordQuestionTextbox" ForeColor="red" Display="Static"
                    ErrorMessage="Required" />
            </td>
        </tr>
        <tr>
            <td>
                Password Answer:
            </td>
            <td>
                <asp:TextBox ID="PasswordAnswerTextbox" runat="server" />
            </td>
            <td>
                <asp:RequiredFieldValidator ID="PasswordAnswerRequiredValidator" runat="server" ControlToValidate="PasswordAnswerTextbox"
                    ForeColor="red" Display="Static" ErrorMessage="Required" />
            </td>
        </tr>
        <% } %>
        <tr>
            <td>
            </td>
            <td>
                <asp:Button ID="CreateUserButton" Text="Create User" OnClick="CreateUser_OnClick"
                    runat="server" />
            </td>
        </tr>
    </table>
    </form>


雙擊“Create User”進入:

  1. public void CreateUser_OnClick(object sender, EventArgs args)  
  2.         {  
  3.             // Create new user and retrieve create status result.  
  4.   
  5.   
  6.             MembershipCreateStatus status;  
  7.             string passwordQuestion = "";  
  8.             string passwordAnswer = "";  
  9.   
  10.             if (Membership.RequiresQuestionAndAnswer)  
  11.             {  
  12.                 passwordQuestion = PasswordQuestionTextbox.Text;  
  13.                 passwordAnswer = PasswordAnswerTextbox.Text;  
  14.             }  
  15.   
  16.             try  
  17.             {  
  18.                 MembershipUser newUser = Membership.CreateUser(UsernameTextbox.Text, PasswordTextbox.Text,  
  19.                                                                EmailTextbox.Text, passwordQuestion,  
  20.                                                                passwordAnswer, trueout status);  
  21.                 if (newUser == null)  
  22.                 {  
  23.                     Msg.Text = GetErrorMessage(status);  
  24.                 }  
  25.                 else  
  26.                 {  
  27.                     Response.Redirect("Default.aspx");  
  28.                 }  
  29.             }  
  30.             catch  
  31.             {  
  32.                 Msg.Text = "An exception occurred creating the user.";  
  33.             }  
  34.         }  
  35.   
  36.         public string GetErrorMessage(MembershipCreateStatus status)  
  37.         {  
  38.             switch (status)  
  39.             {  
  40.                 case MembershipCreateStatus.DuplicateUserName:  
  41.                     return "Username already exists. Please enter a different user name.";  
  42.   
  43.                 case MembershipCreateStatus.DuplicateEmail:  
  44.                     return "A username for that e-mail address already exists. Please enter a different e-mail address.";  
  45.   
  46.                 case MembershipCreateStatus.InvalidPassword:  
  47.                     return "The password provided is invalid. Please enter a valid password value.";  
  48.   
  49.                 case MembershipCreateStatus.InvalidEmail:  
  50.                     return "The e-mail address provided is invalid. Please check the value and try again.";  
  51.   
  52.                 case MembershipCreateStatus.InvalidAnswer:  
  53.                     return "The password retrieval answer provided is invalid. Please check the value and try again.";  
  54.   
  55.                 case MembershipCreateStatus.InvalidQuestion:  
  56.                     return "The password retrieval question provided is invalid. Please check the value and try again.";  
  57.   
  58.                 case MembershipCreateStatus.InvalidUserName:  
  59.                     return "The user name provided is invalid. Please check the value and try again.";  
  60.   
  61.                 case MembershipCreateStatus.ProviderError:  
  62.                     return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";  
  63.   
  64.                 case MembershipCreateStatus.UserRejected:  
  65.                     return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";  
  66.   
  67.                 default:  
  68.                     return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";  
  69.             }  
public void CreateUser_OnClick(object sender, EventArgs args)
        {
            // Create new user and retrieve create status result.


            MembershipCreateStatus status;
            string passwordQuestion = "";
            string passwordAnswer = "";

            if (Membership.RequiresQuestionAndAnswer)
            {
                passwordQuestion = PasswordQuestionTextbox.Text;
                passwordAnswer = PasswordAnswerTextbox.Text;
            }

            try
            {
                MembershipUser newUser = Membership.CreateUser(UsernameTextbox.Text, PasswordTextbox.Text,
                                                               EmailTextbox.Text, passwordQuestion,
                                                               passwordAnswer, true, out status);
                if (newUser == null)
                {
                    Msg.Text = GetErrorMessage(status);
                }
                else
                {
                    Response.Redirect("Default.aspx");
                }
            }
            catch
            {
                Msg.Text = "An exception occurred creating the user.";
            }
        }

        public string GetErrorMessage(MembershipCreateStatus status)
        {
            switch (status)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }

(9)點擊“項目”選擇“ASP.NET配置”,選擇“安全”,之後彈出的內容將以圖片展示:






最後點擊“完成”。

角色管理

Roles類

ASP.NET網站管理配置工具(WAST)提供一個可視化界面用於建立用戶和角色的關係。角色管理API中包括多個類,最重要的是Roles類。該類分割了用戶界面與執行底層數據訪問的角色管理提供程序,從而爲快速實現多種數據源存儲的角色管理應用提供了技術支持。

Roles類具有以下功能:

1.創建和管理角色

2.將角色信息存儲在SQL Server或其他數據源中

3.獲取有關角色管理配置的詳細內容

Roles類的主要方法:


創建Roles類的代碼文件:

在“WebApplocation”右鍵點擊“添加”——“新建項”,彈出“添加新項”,添加新的項目,更改名稱。

之後輸入代碼:




發佈了39 篇原創文章 · 獲贊 10 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章