ASP.NET 2.0 角色控制与管理

1.       认证与授权机制

l         ASP.NET 2.0安全必要性

对于网站而言,用户身份认证与权限管理是非常重要的部分。通过用户名和密码,对用户进行身份验证,并指派他可访问的资源,这部分工作一直都是网站开发的重要内容。

在另外一些情况下,需要根据用户的身份进行权限识别,不同用户访问相同页面,也需要显示不同内容。这设计到用户权限管理部分,也是网站开发的核心内容。

l         ASP.NET 2.0角色控制概述

ü         ASP.NET 2.0membershiprole manager能够非常好的解决这个问题,不但可以对用户的登陆信息进行统一管理,还可以就用户的权限进行分类管理,让开发者方便的就网站权限与安全性进行设定。这种设定以前都需要我们自己写一个库,但是现在就可以快速的进行设定。

ü         ASP.NET 2.0Login控件更提供了一种非常方便的建造登陆与用户管理信息的方法。

l         认证与授权

ASP.NET 通过与IIS协同工作来进行授权管理。共用两种身份认证方式。

ü        通过查询acls列表或者许可证来判断该访问是否拥有浏览的权利。(acls指可以访问的列表,这个列表记录了访问者是谁,他是否可以访问我们的资源。)

ü        通过URL认证

l         认证方式

当用户以访问某网站的时候。两种授权方式会分别进行不同的动作。第一种认证方式会根据用户的登陆信息来判定asp.net针对该用户所指定的系统账号,然后再判断该系统账号是否对被请求的本地资源有访问权限。(第一种方式主要是通过IIS的配置来实现的,这里不是本文的重点)。第二种身份认证通过检查ASP.NET 配置文件来进行授权认证。

ASP.NET 的页面认证方式中,可以使用以下三种方式进行身份认证。

取值

描述

None

不进行授权与身份验证

Windows

基于windows身份验证,首先判断windows用户的身份和组

Form

基于cookie的身份认证机制

PassPort

使用PostPort SDK进行二次开发

注:在广域网中不可能使用这种Windows身份验证。域在大也不可能管理的了那么多。

Passport是微软提供的基于广域网的一种识别方式,这种方式比较特殊。有点类似Windows,是指一次登陆处处使用的概念。一旦在Passport登陆以后,所有使用PassPort方式的网站都不需要再进行登陆。身份认证信息都存在你的本地。使用passport的用户都需要对passport sdk进行二次开发。对于一个网站开发来说可能增加了开发的复杂度。所以一般使用Form认证方式就可以了。

通过修改config文件中的authentication属性,可以配置不同的认证方式。

认证方式:

每个网站都有一个Web.nfig文件,这个文件是记录这个网站的配置信息的。其中有这么一段:

<configuration>

       <system.web>

              <authentication mode = “Forms”/>//授权模式,可以是以上表格中的几种取值,确定认证方式。

       </system.web >

</configuration >

ü         Windows认证方式

    Windows认证方式通过使用windowsprincipal类对用户的windows身份进行判定,然后根据用户所属的windows身份组来进行认证。

示例:Windows Authentication(需要在web.config里加上<authentication mode = “Windows”/>

<%@ Page Language="C#" runat=server AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

 

 <script runat=server>

    protected void Page_Load(object sender, EventArgs e)

    {

   

        AuthUser.Text = User.Identity.Name;

        AuthType.Text = User.Identity.AuthenticationType;

    }

 </script>

 

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <span style="font-family: Verdana">使用 Windows Authentication</span><table bordercolor="black"

            rules="all" style="font-size: 8pt; font-family: Verdana; border-collapse: collapse;

            background-color: #ccccff; bordercolor: black" width="700">

            <tr>

                <td>

                    用户:</td>

                <td>

                    <asp:Label ID="AuthUser" runat="server"></asp:Label>

                </td>

            </tr>

            <tr>

                <td>

                    认证方式:</td>

                <td>

                    <asp:Label ID="AuthType" runat="server"></asp:Label>

                </td>

            </tr>

        </table>

   

    </div>

    </form>

</body>

</html>

运行效果:

使用 Windows Authentication

用户:

7EDD5807D52E414"qimu

认证方式:

NTLM

说明:7EDD5807D52E414是计算机名。Qmu是我的用户名

NTLM是指windows登陆方式。

这种方式的好处在于,如果是在域集成的用户中,每个用户登陆自己的PC之后,Server端就可以根据他本人的权限在在域中找到他所对应的权限,然后在他登陆网站的时候,用户不需要再输入一次登陆账号和密码了。局域网中使用较多,广域网中使用比较少。

ü         From认证方式

From认证方式是在窗体内提供用户输入ID和密码的地方,并根据用户输入的ID和密码进行身份认证。

From认证方式同时还使用cookie记录用户的信息,当用户访问其他页面的时候,程序通过访问cookie来获得用户的身份信息。

Ø         From认证方式配置文件

<configuration>

     <system.web>

    <authentication mode="Forms">

      <forms name=".ASPXUSERDEMO" loginUrl="Default2.aspx" protection="All" timeout="60" path = //>

   <!--protection = "[All|None|Encryption|Validation]"-->

 </authentication>

    <authorization>

      <deny users="?" />

    </authorization>

    </system.web>

</configuration>

Ø         From认证方式配置文件讲解

配置文件中的属性意义如下表所示

属性

描述

LoginUrl

指定一个用于登陆的页面,没有认证直接跳过登陆页面时,自动跳转到登陆页面。

Name

Cookie的名字,注意:如果一个服务器有很多应用的话,要给Cookie起不同的名字。

Timeout

Cookie的存活时间默认值是30分钟

Protection

Cookie被保存的方式,不保护起来将会很麻烦!

path

Cookie被保存的时间

Ø         Protection属性

Protection是用来描述Cookie的保存方式,有下列四个可选择项目。

属性

描述

None

不使用任何方法包含Cookie(不提倡)

Encryption

使用Des或者三层DesCookie进行加密,但是并不对Cookie传输中是否被监听或篡改进行监视。

Validation

监视Cookie,保证传输过程中不会被监听或者篡改。但是并不对Cookie进行加密。(发给谁,就只能又谁发回)

All

同时使用EncryptionValidation。(提倡)

Web.config部分:

    <authentication mode="Forms">

      <forms name=".ASPXUSERDEMO" loginUrl="Default2.aspx" protection="All" timeout="60" path = "/"/>

    </authentication>

    <authorization>

      <deny users="?" />

</authorization>

Default2部分:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<%@ Import Namespace="System.Web.Security " %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

 <script language="C#" runat="server">

    protected void Login_Click(object sender, EventArgs e)

    {

        //authenticate user: this samples accepts only one user with

        // a name of qimu and a password of '123'

        if (UserEmail.Value == "qimu" && UserPass.Value == "123")

        {

            FormsAuthentication.RedirectFromLoginPage(UserEmail.Value, PersistCookie.Checked);

        }

        else

        {

            Msg.Text = "用户名密码错误,请重新尝试";

        }

    }

 </script>

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form3" runat="server">

    <div>

        <span style="font-family: Verdana">登陆页</span><table style="font-family: Verdana">

            <tr>

                <td>

                    Email:</td>

                <td>

                    <input id="UserEmail" runat="server" type="text" /></td>

                <td>

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="UserEmail"

                        Display="Static" ErrorMessage="*"></asp:RequiredFieldValidator></td>

            </tr>

            <tr style="color: #000000">

                <td>

                    Password:</td>

                <td>

                    <input id="UserPass" runat="server" type="password" /></td>

                <td>

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="UserPass"

                        Display="Static" ErrorMessage="*"></asp:RequiredFieldValidator></td>

            </tr>

            <tr style="color: #000000">

                <td>

                    记住 Cookie:</td>

                <td>

                    <asp:CheckBox ID="PersistCookie" runat="server" />

                </td>

                <td>

                </td>

            </tr>

        </table>

        <asp:Button ID="Button1" runat="server" OnClick="Login_Click" Text="登陆" />

        <p>

            <asp:Label ID="Msg" runat="server" ForeColor="red"></asp:Label>

        </p>

   

    </div>

    </form>

</body>

</html>

Default3.aspx.cs部分:

    protected void Page_Load(object sender, EventArgs e)

    {

        Welcome.Text = "Hello, " + User.Identity.Name;

    }

Default2部分:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<script language ="C#" runat=server>

    protected void Signout_Click(object sender, EventArgs e)

    {

          FormsAuthentication.SignOut();

          Response.Redirect("Default2.aspx");

    }

</script>

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form3" runat="server">

    <div>

        <span style="font-family: Verdana">使用 Cookie Authentication</span>

            <h3>

                <asp:Label ID="Welcome" runat="server"></asp:Label></h3>

            <asp:Button ID="Button1" runat="server" OnClick="Signout_Click" Text="Signout" />

        </form>

    </div>

    </form>

</body>

</html>

Ø         使用文件记录用户的帐户和密码

用户还可以通过指定可访问的用户名和密码来指定访问用户。

         <authorization>

              <deny users="?" />

         </authorization>

      <authetication>

        <credentials passwordFormat ="SHA1">

          <user name ="Mary" password ="94f85995c7492eec54... "/>

          <user name ="John" password ="5753a98..."

        </credentials>

      </authetication>

Ø         使用文件记录帐户信息

在指定密码的保存方式时,可以之指定密码的存放方式,有3种方式。如下表所示:

Hash类型

描述

Clear

不加密进行存储(不提倡,以防泄露。)

SHA1

使用SHA1进行加密

MD5

使用MD5进行加密

Ø         授权用户与角色

用户访问还可以通过定制访问规则来实现对用户的角色分配。

<authorization>

 <allow users ="someone@www.frontfree.com"/>

 <allow roles ="Admins"/>

 <deny users ="*"/>//拒绝所有用户访问

</authorization>

以上代码指定只有someone@www.frontfree.com的用户可以访问该站点,并且该用户具有的权限是管理员。

Ø         授权用户信息

Wen.config里,同样可以通过配置alldeny属性来对访问用户的Id,访问方法进行设定。

<allow VERB ="POST" users ="John,Mary"/>

<deny VERB ="POST" users ="*"/>

<allow VERB ="GET" users ="*"/>

Ø         User属性的描述

User属性有两种配置方法,如下表所示:

UserName

描述

*

所有用户

匿名用户

Ø         示例:From认证演示:(如上文演示)

2.       使用用户管理控件

l         LoginLoginstatusCreateUserWizard控件示例

Web Config部分:

<authentication mode="Forms"/>

MasterPage.master 部分:

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Using Site Navigation Controls</title>

</head>

<body>

    <form id="form1" runat="server">

        <table border="0" cellpadding="0" cellspacing="0" style="width: 100%; height: 80%">

            <tr height = "20px">

                <td style="width: 100px">

                    <img id="Img1" src="Images/index_r1_c1.jpg" runat="server"/>

               </td>

               <td style="width: 80px; background-color: white" align="center">

                   <asp:LoginStatus ID="LoginStatus2" runat="server" />

               </td>

            </tr>

            <tr>

                <td style="width: 100px">

                   <img id="Img2" src="Images/test.jpg" runat="server"/>

                </td>

                <td style="background-color: white;padding-left:25;padding-top:15" colspan="2" valign="top">

 

                    <asp:ContentPlaceHolder ID = "MainBody" runat ="server">

                    </asp:ContentPlaceHolder>

                </td>

            </tr>

        </table>

    </form>

</body>

</html>

Default.aspx部分:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" Title="Untitled Page" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="MainBody" Runat="Server">

 <asp:LoginView ID="LoginView1" runat="server">

    <loggedintemplate>

      <h1>

        <asp:loginname id="LoginName1" runat="server" formatstring="Welcome {0}" />

      </h1>

    </loggedintemplate>

    <anonymoustemplate>

      <h1>Welcome to Login Controls</h1>

      <asp:login ID="Login1" runat="server" createuserurl="CreateUser.aspx" createusertext="Create a New Account" />

    </anonymoustemplate>

 </asp:LoginView>

</asp:Content>

Login.aspx部分:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" Title="Untitled Page" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="MainBody" Runat="Server">

    <asp:Login ID="Login1" runat="server" BackColor="#F7F7DE" BorderColor="#CCCC99" BorderStyle="Solid"

        BorderWidth="1px" CreateUserText="创建用户" CreateUserUrl="~/CreateUser.aspx" Font-Names="Verdana"

        Font-Size="10pt">

        <TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

    </asp:Login>

</asp:Content>

CreateUser.aspx部分:

<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPage.master" Title="Untitled Page" CodeFile="CreateUser.aspx.cs" Inherits="Default2" %>

 

 

<asp:Content ID="Content1" ContentPlaceHolderID="MainBody" Runat="Server">

    <asp:CreateUserWizard ID="CreateUserWizard1" runat="server" ContinueDestinationPageUrl="~/Default.aspx">

        <WizardSteps>

            <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">

            </asp:CreateUserWizardStep>

            <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">

            </asp:CompleteWizardStep>

        </WizardSteps>

    </asp:CreateUserWizard>

</asp:Content>

只是拖动控件 没有添加太多代码即可!

l         LoginView示例

l         ChangePassWord示例

3.       成员资格与角色管理

l         成员管理

成员管理特性基于menbershipmenbershipuser两个类。可以使用menbership类为asp.net创建用户

Membership类还可以完成一下工作:

ü         建立一个新的menbershipuser

ü         可以对用户身份进行验证

ü         找回一个membershipuser实例

ü         更新一个membershipuser示例

ü         通过不同条件寻找一个用户

ü         获得当前在线用户数量

ü         删除一个已经不再需要的帐户

简单的讲,merbershipmembershipuser是一对配合非常好的类。Merbership用来管理membershipuser,由它来建立一些用户,对这些用户进行分配。Membershipuser就是每个用户的具体信息。通过他的一些信息我们可以管理用户。

对于一个Merbership类,可以完成一下工作:

ü         访问一个merbership示例的属性

ü         找回一个用户的密码

ü         修改一个用户的密码

ü         修改一个用户的密码问题以及密码问题的答案

ü         为一个已经因为多次尝试密码失败而锁定的用户解除锁定。

下文(角色管理以后)的示例我们分别演示如何通过简单的编程来实现这些功能。

l         角色管理

角色管理基于role类实现。通过角色管理类,可以实现以下工作:

ü        新建一种用户角色

ü        删除一种用户角色

ü        给一个用户分配角色

ü        去除一个用户的角色

ü        判断用户是否被授权给一个特殊的角色

ü        在一种角色中寻找一个用户

ü        从一个用户信息中获得他所具有的角色信息

示例:创建用户(通过调用MerbershipCreateuser方法可以创建用户。需要注意的是membership类对安全性比较高,所以密码要求长度大于7位,并且需要至少包括一个特殊字符。)

Web.config文件:

<configuration>

     <appSettings/>

     <connectionStrings/>

     <system.web>

         <compilation debug="true"/>

         <authentication mode="Forms"/>//授权模式描述

         <roleManager enabled="true"/>//程序中需要对角色进行管理,所以这里需要设置属性为true。

     </system.web>

     <location path="secured">

         <system.web>

              <authorization>

                   <deny users="?"/>//路径描述,限制路径安全性的描述,secured这个路径对匿名用户禁止,对所有用户可用。

                   <allow users="*"/>

              </authorization>

         </system.web>

     </location>

     <location path="administrators_role">

         <system.web>

              <authorization>

                   <allow roles="Administrators"/>//只有Administrators可以访问,其他所有用户都禁止。

                   <deny users="*"/>

              </authorization>

         </system.web>

     </location>

</configuration>

CreatingUsers.aspx部分:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CreatingUsers.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<script runat="server">

    protected void btnCreate_Click(object sender, EventArgs e)

    {

        string userName = txtUserId.Text;

        string password = txtPassword.Text;

        string email = txtEmail.Text;

        string passwordQuestion = ddlPasswordQuestion.SelectedValue;

        string passwordAnswer = txtPasswordAnswer.Text;

        MembershipCreateStatus result;

        Membership.CreateUser(userName, password, email, passwordQuestion, passwordAnswer, true,out result);

        lblResults.Visible = true;

        switch (result)

        {

            case MembershipCreateStatus.Success:

                {

                    txtUserId.Text = null;

                    txtPassword.Text = null;

                    txtEmail.Text = null;

                    ddlPasswordQuestion.SelectedIndex = -1;

                    txtPasswordAnswer.Text = null;

                    lblResults.Text = "用户成功创建!";

                    break;

                };

            case MembershipCreateStatus.InvalidUserName:

                {

                    lblResults.Text = "用户名的格式无效。请输入不同的用户名。";

                    break;

                };

            case MembershipCreateStatus.InvalidPassword:

                {

                    lblResults.Text = "密码格式无效。请输入新的密码。";

                    break ;

                };

            case MembershipCreateStatus.InvalidEmail:

                {

                    lblResults.Text = "电子邮件格式无效。请输入不同的用户名。";

                    break;

                };

            case MembershipCreateStatus.InvalidQuestion:

                {

                    lblResults.Text = "密码问题的格式是无效的。请输入一个不同的问题。";

                    break;

                }

            case MembershipCreateStatus.InvalidAnswer:

                {

                    lblResults.Text = "密码答案格式是无效的。请输入不同的答案。";

                    break;

                }

            case MembershipCreateStatus.DuplicateUserName:

                {

                    lblResults.Text = "用户名已被使用。请输入新的用户名。";

                    break;

                };

            case MembershipCreateStatus.DuplicateEmail:

                {

                    lblResults.Text = "电子邮件地址已被使用。请输入一个不同的电子邮件地址。";

                    break ;

                };

            default:

                {

                    lblResults.Text = "创建用户时发生错误!";

                    break ;

                }

        }

    }

</script>

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

    <div><table id="tblLogin" style="border-right: black thin solid; border-top: black thin solid; border-left: black thin solid; width: 422px; border-bottom: black thin solid; height: 189px" cellpadding="1" cellspacing="1">

        <tr>

            <td colspan="2">

                <div style="">

                    <strong><span style="text-decoration: underline">创建新用户</span></strong>

                </div>

            </td>

        </tr>

        <tr>

            <td width="40%">

                用户名:</td>

            <td>

                <asp:TextBox ID="txtUserId" runat="server" Width="100%">username</asp:TextBox>

            </td>

        </tr>

        <tr>

            <td>

                密码:</td>

            <td>

                <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Width="100%"></asp:TextBox>

            </td>

        </tr>

        <tr>

            <td>

                Email:</td>

            <td>

                <asp:TextBox ID="txtEmail" runat="server" Width="100%">myemail@foo.org</asp:TextBox>

            </td>

        </tr>

        <tr>

            <td>

                密码问题</td>

            <td>

                <asp:DropDownList ID="ddlPasswordQuestion" runat="server" Width="100%">

                    <asp:ListItem>你母亲的名字是?</asp:ListItem>

                    <asp:ListItem>你在那里出生的?</asp:ListItem>

                    <asp:ListItem>你最喜欢吃什么?</asp:ListItem>

                </asp:DropDownList>

            </td>

        </tr>

        <tr>

            <td>

                答案</td>

            <td>

                <asp:TextBox ID="txtPasswordAnswer" runat="server" Width="100%"></asp:TextBox>

            </td>

        </tr>

        <tr>

            <td colspan="2" style="">

                <asp:Button ID="btnCreate" runat="server" OnClick="btnCreate_Click" Text="点击创建用户" />

            </td>

        </tr>

    </table>

        <br />

        <br />

        <asp:Label ID="lblResults" runat="server" Visible="false">Results:</asp:Label>&nbsp;<br />

   

    </div>

    </form>

</body>

</html>

用户登陆以及访问用户属性:

下面使用Membership中的validatause方法来确认用户是否合法。Membershipuser类,用以对获得用户的属性信息。

接上面例子:

login.aspx.cs内容:

    protected void Page_Load(object sender, EventArgs e)

    {

        this.DataBind();

}

login.aspx内容;

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

 

<script runat="server">

    protected void btnLogin_Click(object sender, EventArgs e)

    {

        string userName = txtUserId.Text;

        string password = txtPassword.Text;

        if (Membership.ValidateUser(userName, password))

        {

            if (!(Request.QueryString.Get("ReturnUrl") == null))

            {

                FormsAuthentication.RedirectFromLoginPage(userName, false);

            }

            else

            {

                FormsAuthentication.SetAuthCookie(userName, false);

                Response.Redirect("~/secured/menu.aspx");

            }

        }

        else

        {

            lblResults.Visible = true;

            lblResults.Text = "登录失败!请重新输入您的信息,然后再试一次。";

            if (! (Membership.GetUser(userName)==null))

            {

                if (Membership.GetUser(userName).IsLockedOut == true)

                {

                    lblResults.Text = lblResults.Text + " <b>您的帐户已被锁定。</b>";

                }

            }

        }

    }

</script>

 

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

    <div><table id="tblLogin" style="border-right: black thin solid; border-top: black thin solid; border-left: black thin solid; border-bottom: black thin solid" cellpadding="1" cellspacing="1">

        <tr>

            <td colspan="2">

                <div style="">

                    <strong><span style="text-decoration: underline">登陆网站</span></strong>

                </div>

            </td>

        </tr>

        <tr>

            <td width="40%">

                请输入用户名:</td>

            <td>

                <asp:TextBox ID="txtUserId" runat="server" Width="100%"></asp:TextBox>

            </td>

        </tr>

        <tr>

            <td>

                请输入密码:</td>

            <td>

                <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Width="100%"></asp:TextBox>

            </td>

        </tr>

        <tr>

            <td colspan="2" style="">

                <asp:Button ID="btnLogin" runat="server" OnClick="btnLogin_Click" Text="点击进入" />

            </td>

        </tr>

        <tr>

            <td colspan="2">

                <asp:Label ID="lblNumberOfAttempts" runat="server" Text='<%# "锁定应用后,用户的第" + Membership.Provider.MaxInvalidPasswordAttempts + " </B>次尝试登录失败。" %>'></asp:Label>

            </td>

        </tr>

    </table>

        <br />

        <a href="CreatingUsers.aspx">点击这里创建一个新用户</a>

        <br />

        <br />

        <asp:Label ID="lblResults" runat="server" BackColor="Red" Visible="false">Results:</asp:Label>&nbsp;</div>

    </form>

</body>

</html>

删除用户;可以通过调用MembershipDeleteuser方法来删除一个用户。并通过返回值来判断删除是否成功。

DeleteUser.aspx内容;

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DeleteUser.aspx.cs" Inherits="secured_Default3" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

 

<script runat="server">

    protected void btnDeleteCurrentUser_Click(object sender, EventArgs e)

    {

        if (Membership.DeleteUser(User.Identity.Name))

        {

            FormsAuthentication.SignOut();

            Roles.DeleteCookie();

            Response.Redirect("~/CreatingUsers.aspx");

        }

        else

        {

            lblResult.Visible = true;

            lblResult.Text = "用户成员没有删除。";

        }

    }

</script>

 

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <br />

            <asp:Button ID="btnDeleteCurrentUser" runat="server" OnClick="btnDeleteCurrentUser_Click"

                Text="点击删除登录用户" />

            <br />

            <asp:Label ID="lblResult" runat="Server" BackColor="Red" Visible="false"></asp:Label>

            <br />

            <br />

            <div id="result_box" dir="ltr" style="">

                点击上面的按钮会删除登录的用户。

                <br />

                该网页将让您登录,并返回您的页面,您可以创建一个新的用户。</div>

        </div>

    </form>

</body>

</html>

其他部分:

UpdateUserProperties.aspx内容:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UpdateUserProperties.aspx.cs" Inherits="secured_Default2" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

 

<script runat="server">

    protected void linkLogout_Click(object sender, EventArgs e)

    {

        FormsAuthentication.SignOut();

        Roles.DeleteCookie();

        FormsAuthentication.RedirectToLoginPage();

    }

    protected void DetailsView1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)

    {

        //需要处理的手动更新,因为MembershipUser没有parameterless构造 

        MembershipUser memUser = Membership.GetUser();

        memUser.Email = e.NewValues[0].ToString();

        memUser.Comment = e.NewValues[1].ToString();

        Membership.UpdateUser(memUser);

        e.Cancel = true;

        DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);

    }

</script>

 

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <table id="tblUpdateUserProperties" cellpadding="0" cellspacing="0">

            <tr>

                <td>

                    <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateEditButton="True"

                        AutoGenerateRows="False" DataSourceID="ObjectDataSource1" Height="50px" OnItemUpdating="DetailsView1_ItemUpdating"

                        Width="125px">

                        <Fields>

                            <asp:BoundField DataField="CreationDate" HeaderText="创建日期" ReadOnly="True"

                                SortExpression="CreationDate" />

                            <asp:BoundField DataField="LastActivityDate" HeaderText="激活日期" ReadOnly="True"

                                SortExpression="LastActivityDate" />

                            <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />

                            <asp:BoundField DataField="ProviderUserKey" HeaderText="服务器用户密码" ReadOnly="True"

                                SortExpression="ProviderUserKey" />

                            <asp:BoundField DataField="Comment" HeaderText="批注" SortExpression="Comment" />

                            <asp:BoundField DataField="IsOnline" HeaderText="是否在线" ReadOnly="True" SortExpression="IsOnline" />

                            <asp:BoundField DataField="IsApproved" HeaderText="是否批准" ReadOnly="True" SortExpression="IsApproved" />

                            <asp:BoundField DataField="IsLockedOut" HeaderText="是否锁定" ReadOnly="True"

                                SortExpression="IsLockedOut" />

                            <asp:BoundField DataField="PasswordQuestion" HeaderText="密码问题" ReadOnly="True"

                                SortExpression="PasswordQuestion" />

                            <asp:BoundField DataField="ProviderName" HeaderText="ProviderName" ReadOnly="True"

                                SortExpression="ProviderName" />

                            <asp:BoundField DataField="LastLoginDate" HeaderText="上次登入时间" ReadOnly="True"

                                SortExpression="LastLoginDate" />

                            <asp:BoundField DataField="LastLockoutDate" HeaderText="上次锁定时间" ReadOnly="True"

                                SortExpression="LastLockoutDate" />

                            <asp:BoundField DataField="UserName" HeaderText="用户名" ReadOnly="True" SortExpression="UserName">

                                <ItemStyle Font-Bold="True" />

                                <HeaderStyle Font-Bold="True" />

                            </asp:BoundField>

                            <asp:BoundField DataField="LastPasswordChangedDate" HeaderText="上次密码修改时间"

                                ReadOnly="True" SortExpression="LastPasswordChangedDate" />

                        </Fields>

                        <HeaderTemplate>

                            <div style="">

                                <strong>用户属性</strong>

                            </div>

                        </HeaderTemplate>

                    </asp:DetailsView>

                    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DataObjectTypeName="System.Web.Security.MembershipUser"

                        SelectMethod="GetUser" TypeName="System.Web.Security.Membership"></asp:ObjectDataSource>

                </td>

            </tr>

        </table>

        <hr />

        <br />

        <div align="center">

            <asp:LinkButton ID="linkLogout" runat="server" OnClick="linkLogout_Click">点击退出</asp:LinkButton>

        </div>

   

    </div>

    </form>

</body>

</html>

解除锁定:

UnlockUser.aspx.cs部分:

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

            txtUserName.Text = User.Identity.Name;

}

UnlockUser.aspx部分;

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UnlockUser.aspx.cs" Inherits="secured_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

 

<script runat="server">

    protected void btnUnlockUser_Click(object sender, EventArgs e)

    {

        MembershipUser memUser = Membership.GetUser(txtUserName.Text);

        if (!(memUser == null) && (memUser.IsLockedOut == true))

            memUser.UnlockUser();

        //刷新选择用户的信息

        DetailsView1.DataBind();

    }

    protected void linkLogout_Click(object sender, EventArgs e)

    {

        FormsAuthentication.SignOut();

        Roles.DeleteCookie();

        FormsAuthentication.RedirectToLoginPage();

    }

</script>

 

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <table id="tblUpdateUserProperties" cellpadding="0" cellspacing="0">

            <tr>

                <td>

                    <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataSourceID="ObjectDataSource1"

                        Height="50px" Width="125px">

                        <Fields>

                            <asp:BoundField DataField="CreationDate" HeaderText="创建日期" ReadOnly="True"

                                SortExpression="CreationDate" />

                            <asp:BoundField DataField="LastActivityDate" HeaderText="激活时间" SortExpression="LastActivityDate" />

                            <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />

                            <asp:BoundField DataField="ProviderUserKey" HeaderText="服务器用户密码" ReadOnly="True"

                                SortExpression="ProviderUserKey" />

                            <asp:BoundField DataField="Comment" HeaderText="批注" SortExpression="Comment" />

                            <asp:CheckBoxField DataField="IsLockedOut" HeaderText="是否锁定" ReadOnly="True"

                                SortExpression="IsLockedOut">

                                <HeaderStyle Font-Bold="True" />

                            </asp:CheckBoxField>

                            <asp:CheckBoxField DataField="IsOnline" HeaderText="是否在线" ReadOnly="True" SortExpression="IsOnline" />

                            <asp:BoundField DataField="PasswordQuestion" HeaderText="密码问题" ReadOnly="True"

                                SortExpression="PasswordQuestion" />

                            <asp:BoundField DataField="ProviderName" HeaderText="ProviderName" ReadOnly="True"

                               SortExpression="ProviderName" />

                            <asp:BoundField DataField="LastLoginDate" HeaderText="上次登入时间" SortExpression="LastLoginDate" />

                            <asp:BoundField DataField="LastLockoutDate" HeaderText="上次锁定时间" ReadOnly="True"

                                SortExpression="LastLockoutDate" />

                            <asp:BoundField DataField="UserName" HeaderText="用户名" ReadOnly="True" SortExpression="UserName">

                                <ItemStyle Font-Bold="True" />

                                <HeaderStyle Font-Bold="True" />

                            </asp:BoundField>

                            <asp:BoundField DataField="LastPasswordChangedDate" HeaderText="上次修改密码时间"

                                ReadOnly="True" SortExpression="LastPasswordChangedDate" />

                            <asp:CheckBoxField DataField="IsApproved" HeaderText="是否批准" SortExpression="IsApproved" />

                        </Fields>

                        <HeaderTemplate>

                            <div style="">

                                <strong>用户属性</strong>

                            </div>

                        </HeaderTemplate>

                        <FooterTemplate>

                            <div style="">

                                <asp:Button ID="btnUnlockUser" runat="server" OnClick="btnUnlockUser_Click" Text="解锁当前显示帐户" />

                            </div>

                        </FooterTemplate>

                    </asp:DetailsView>

                    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetUser"

                        TypeName="System.Web.Security.Membership">

                        <SelectParameters>

                            <asp:ControlParameter ControlID="txtUserName" DefaultValue=" " Name="username" PropertyName="Text"

                                Type="String" />

                        </SelectParameters>

                    </asp:ObjectDataSource>

                </td>

            </tr>

            <tr>

                <td>

                    请输入您要显示的用户名:

                    <asp:TextBox ID="txtUserName" runat="server" Width="226px"></asp:TextBox>

                </td>

            </tr>

        </table>

        <div align="center">

            <asp:LinkButton ID="linkLogout" runat="server" OnClick="linkLogout_Click">点击返回</asp:LinkButton>

        </div>

   

    </div>

    </form>

</body>

</html>

目录部分;

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="menu.aspx.cs" Inherits="secured_Default4" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

    <div style="">

        <table>

            <tr>

                <td style="width: 100px">

                    <a href="DisplayUserProperties.aspx">用户属性</a></td>

                <td style="width: 100px">

                    <a href="UpdateUserProperties.aspx">修改用户</a></td>

            </tr>

            <tr>

                <td style="width: 100px">

                    <a href="DeleteUser.aspx">删除用户</a></td>

                <td style="width: 100px">

                    <a href="UnlockUser.aspx">解锁用户</a></td>

            </tr>

            <tr>

                <td style="width: 100px">

                    <a href="Add_Delete_Roles.aspx">添加角色</a></td>

                <td style="width: 100px">

                    <a href="Add_Delete_UserRoles.aspx">添加角色用户</a></td>

            </tr>

            <tr>

                <td style="width: 100px">

                    <a href="IsInRole.aspx">是否角色用户</a></td>

            </tr>

        </table>

   

    </div>

    </form>

</body>

</html>

显示用户信息:

DisplayUserProperties.aspx.cs部分;

    protected MembershipUser memUser;

    protected void Page_Load(object sender, EventArgs e)

    {

       

        memUser = Membership.GetUser();

}

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DisplayUserProperties.aspx.cs" Inherits="secured_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<script runat="server">

   

    protected void linkLogout_Click(object sender, EventArgs e)

    {

        FormsAuthentication.SignOut();

        Roles.DeleteCookie();

        FormsAuthentication.RedirectToLoginPage();

    }

   

</script>

 

<head runat="server">

    <title>用户属性</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <table id="tblLogin" cellpadding="0" cellspacing="0">

            <tr>

                <td colspan="2" style="border-right: black thin solid; border-top: black thin solid;

                    border-left: black thin solid">

                    <div style="">

                        <strong><span style="text-decoration: underline">用户属性</span></strong>

                    </div>

                </td>

            </tr>

            <tr>

                <td class="lcol" width="40%">

                    用户名:</td>

                <td class="rcol">

                    <% = Server.HtmlEncode(memUser.UserName) %>

                </td>

            </tr>

            <tr>

                <td class="lcol">

                    Email:</td>

                <td class="rcol">

                    <% = Server.HtmlEncode(memUser.Email) %>

                </td>

            </tr>

            <tr>

                <td class="lcol">

                    批准用户?</td>

                <td class="rcol">

                    <% =(memUser.IsApproved == true ? "批准" : "不批准")%>

                </td>

            </tr>

            <tr>

                <td class="lcol">

                    密码问题:</td>

                <td class="rcol">

                    <% = Server.HtmlEncode(memUser.PasswordQuestion) %>

                </td>

            </tr>

            <tr>

                <td class="lcol">

                    是否在线?/td>

                <td class="rcol">

                    <% =(memUser.IsOnline == true ? "在线" : "不在线")%>

                </td>

            </tr>

            <tr>

                <td class="lcol">

                    创建用户时间 (本地服务器时间):</td>

                <td class="rcol">

                    <% = memUser.CreationDate.ToString("F") %>

                </td>

            </tr>

            <tr>

                <td class="lcol">

                    上次用户登陆时间(本地服务器时间):</td>

                <td class="rcol">

                    <% = memUser.LastLoginDate.ToString("F") %>

                </td>

            </tr>

            <tr>

                <td class="lcol">

                    用户最后系统时间(本地服务器时间):</td>

                <td class="rcol">

                    <% = memUser.LastActivityDate.ToString("F") %>

                </td>

            </tr>

            <tr>

                <td class="lcol" style="border-bottom: black thin solid">

                    在最后一次更改密码(本地服务器时间):</td>

                <td class="rcol" style="border-bottom: black thin solid">

                    <% = memUser.LastPasswordChangedDate.ToString("F") %>

                </td>

            </tr>

        </table>

        <hr />

        <br />

        <div align="center">

            <asp:LinkButton ID="linkLogout" runat="server" OnClick="linkLogout_Click">点击退出</asp:LinkButton>

        </div>

   

    </div>

    </form>

</body>

</html>

ü         角色管理是基于认证用户身份与权限的一种管理方式。下面的几个例子使用角色管理,添加和删除角色。

添加和删除角色:通过使用rolescreatroledeleterole方法可以添加和删除角色,同时还可以调用。

为用户配置角色属性:可以通过roles类的addusertoroleremoveuserfromrole方法来为用户指定一个角色或者移除一个角色。

接上例:

添加删除角色:

Add_Delete_Roles.aspx.cs部分:

    protected void Page_Load(object sender, EventArgs e)

    {

        if(!Page.IsPostBack)

            if(!Roles.RoleExists("Administrators"))

                txtCreateRole.Text = "Administrators";

    }

Add_Delete_Roles.aspx部分:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Add_Delete_Roles.aspx.cs" Inherits="secured_Default2" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<script runat="server">

    protected void btnCreateRole_Click(object sender, EventArgs e)

    {

        string roleName = txtCreateRole.Text;

        try

        {

            Roles.CreateRole(roleName);

            lblResults.Text = null;

            lblResults.Visible = false;

            txtCreateRole.Text = null;

        }

        catch(Exception ex)

        {

            lblResults.Text = "Could not create the role: " + Server.HtmlEncode(ex.Message);

            lblResults.Visible = true;

        }   

        RefreshAvailableRolesListBox();

    }

    protected void btnDeleteRole_Click(object sender, EventArgs e)

    {

        if (lbxAvailableRoles.SelectedIndex != -1)

        {

            try

            {

                Roles.DeleteRole(lbxAvailableRoles.SelectedValue);

                lblResults.Text = null;

                lblResults.Visible = false;

            }

            catch(Exception ex)

            {

                lblResults.Text = "无法删除的角色: " + Server.HtmlEncode(ex.Message);

                lblResults.Visible = true;

            }

        }

        RefreshAvailableRolesListBox();

    }

    protected void RefreshAvailableRolesListBox()

    {

        lbxAvailableRoles.SelectedIndex = -1;

        lbxAvailableRoles.DataSource = Roles.GetAllRoles();

        lbxAvailableRoles.DataBind();

        if (lbxAvailableRoles.Items.Count == 0)

        {

            lblRoleInfoText.Text = "目前没有任何角色在当前应用程序中";

            lbxAvailableRoles.Visible = false;

            btnDeleteRole.Visible = false;

        }

        else

        {

            lblRoleInfoText.Text = "可用角色如下所示;";

            lbxAvailableRoles.Visible = true;

            btnDeleteRole.Visible = true;

        }

    }

    protected void Page_Init(object sender, EventArgs e)

    {

        RefreshAvailableRolesListBox();

    }

</script>

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <table id="Table1" cellpadding="1" cellspacing="1" style="border-right: black thin solid;

            border-top: black thin solid; border-left: black thin solid; border-bottom: black thin solid">

            <tr>

                <td>

                    <b>输入新的角色名称:</b>

                </td>

                <td>

                    <asp:TextBox ID="txtCreateRole" runat="server"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td colspan="2" style="">

                    <asp:Button ID="btnCreateRole" runat="server" OnClick="btnCreateRole_Click" Text="创建角色" />

                </td>

            </tr>

            <tr>

                <td>

                    <span style="font-size: 10pt">&nbsp;</span></td>

            </tr>

            <tr style="font-size: 10pt">

                <td colspan="2" style="">

                    <b>

                        <asp:Label ID="lblRoleInfoText" runat="server" Visible="true"></asp:Label></b>

                </td>

            </tr>

            <tr style="font-size: 12pt">

                <td colspan="2" style="">

                    <asp:ListBox ID="lbxAvailableRoles" runat="server"></asp:ListBox>

                </td>

            </tr>

            <tr style="font-size: 12pt">

                <td>

                    &nbsp;</td>

            </tr>

            <tr style="font-size: 12pt">

                <td colspan="2" style="">

                    <asp:Button ID="btnDeleteRole" runat="server" OnClick="btnDeleteRole_Click" Text="删除选中角色" />

                </td>

            </tr>

        </table>

        <br />

        <br />

        <asp:Label ID="lblResults" runat="server" ForeColor="Red" Visible="false">Results:</asp:Label>

        <br />

        <a href="Add_Delete_UserRoles.aspx">点击此处管理角色的登录的用户。.</a>

        <br />

        <small><span style="font-size: 12pt">(注:网页上的样本表明授权,你将需要添加的角色称为“管理员” , “一般用户”和“超级用户”

            。 ) </span></small>

   

    </div>

    </form>

</body>

</html>

添加用户角色类型:

Add_Delete_UserRoles.aspx部分:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Add_Delete_UserRoles.aspx.cs" Inherits="secured_Default3" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

 

<script runat="server">

    protected void btnAddUserToRole_Click(object sender, EventArgs e)

    {

        if (lbxAvailableRoles.SelectedIndex != -1)

        {

            string selectedRole= lbxAvailableRoles.SelectedValue;

           if (!Roles.IsUserInRole(selectedRole))

            {

                try

                {

                    Roles.AddUserToRole(User.Identity.Name, selectedRole);

                    RefreshCurrentRolesListBox();

                }

                catch(Exception ex)

                {

                    lblResults.Text = "不能添加用户到这个角色:" + Server.HtmlEncode(ex.Message);

                    lblResults.Visible = true;

                }

            }

            else

                lbxAvailableRoles.SelectedIndex = -1;

        }

    }

    protected void btnDeleteUserFromRole_Click(object sender, EventArgs e)

    {

        string selectedRole= lbxUserRoles.SelectedValue;

        if (lbxUserRoles.SelectedIndex != -1)

        {

            try

            {

                Roles.RemoveUserFromRole(User.Identity.Name, selectedRole);

                RefreshCurrentRolesListBox();

            }

            catch(Exception ex)

            {

                lblResults.Text = "Could not remove the user from the role: " + Server.HtmlEncode(ex.Message);

                lblResults.Visible = true;

            }

        }

    }

    protected void Page_Init(object sender, EventArgs e)

    {

        RefreshAvailableRolesListBox();

        RefreshCurrentRolesListBox();

    }

    protected void RefreshAvailableRolesListBox()

    {

        lbxAvailableRoles.SelectedIndex = -1;

        lbxAvailableRoles.DataSource = Roles.GetAllRoles();

        lbxAvailableRoles.DataBind();

        if (lbxAvailableRoles.Items.Count == 0)

        {

            lblRoleInfoText.Text = "There are currently no roles for this application.";

            lbxAvailableRoles.Visible = false;

            btnAddUserToRole.Visible = false;

        }

        else

        {

            lblRoleInfoText.Text = "The list of available roles is shown below.";

            lbxAvailableRoles.Visible = true;

            btnAddUserToRole.Visible = true;

        }

    }

    protected void RefreshCurrentRolesListBox()

    {

        lbxUserRoles.SelectedIndex = -1;

       //同样可以使用Roles.GetRolesForUser();

        lbxUserRoles.DataSource = ((RolePrincipal)User).GetRoles();

        lbxUserRoles.DataBind();

       

        if (lbxUserRoles.Items.Count == 0)

        {

            lblUserRoleInfoText.Text = "The user currently does not belong to any roles.";

            lbxUserRoles.Visible = false;

            btnDeleteUserFromRole.Visible = false;

        }

        else

        {

            lblUserRoleInfoText.Text = "The user is a member of the following roles.";

            lbxUserRoles.Visible = true;

            btnDeleteUserFromRole.Visible = true;

        }

    } 

</script>

 

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <table id="Table1" cellpadding="1" cellspacing="1" style="border-right: black thin solid;

            border-top: black thin solid; border-left: black thin solid; border-bottom: black thin solid">

            <tr>

                <td style="">

                    <b>

                        <asp:Label ID="lblRoleInfoText" runat="server"></asp:Label></b>

                </td>

            </tr>

            <tr>

                <td style="">

                    <asp:ListBox ID="lbxAvailableRoles" runat="server"></asp:ListBox><span style="text-decoration: underline">

                    </span>

                </td>

            </tr>

            <tr style="text-decoration: underline">

                <td style="">

                    <asp:Button ID="btnAddUserToRole" runat="server" OnClick="btnAddUserToRole_Click"

                        Text="Add Current User to Selected Role" />

                </td>

            </tr>

            <tr>

                <td>

                    &nbsp;</td>

            </tr>

            <tr>

                <td style="">

                    <b>

                        <asp:Label ID="lblUserRoleInfoText" runat="server" Visible="true"></asp:Label></b>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:ListBox ID="lbxUserRoles" runat="server" Width="100%"></asp:ListBox>

                </td>

            </tr>

            <tr>

                <td align="center">

                    <asp:Button ID="btnDeleteUserFromRole" runat="server" OnClick="btnDeleteUserFromRole_Click"

                        Text="Delete User from Selected Role" />

                </td>

            </tr>

        </table>

        <br />

        <a href="Add_Delete_Roles.aspx">点击此处管理角色的应用程序。</a>

        <br />

        <br />

        <a href="IsInRole.aspx">点击这里查看的结果, IsInRole检查当前用户。</a>

        <br />

        <br />

        <a href="../administrators_role/Administrators_Page.aspx">点击这里进入“Administrators-only”网页

(注-您必须在管理员角色下去登陆该页面) 。 <br /></a>

        <br />

        <br />

        <asp:Label ID="lblResults" runat="server" ForeColor="Red" Visible="false">Results:</asp:Label>

   

    </div>

    </form>

</body>

</html>

判断角色类型:

IsInRole.aspx部分:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="IsInRole.aspx.cs" Inherits="secured_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <table cellpadding="0" cellspacing="0">

            <tr>

                <td style="border-right: black thin solid; border-top: black thin solid; border-left: black thin solid">

                    <b>Role Name</b>

                </td>

                <td style="border-right: black thin solid; border-top: black thin solid">

                    <b>Is User In Role?</b>

                </td>

            </tr>

           <tr>

                <td class="lcol">

                    Administrators</td>

                <td class="rcol">

                    <asp:Label ID="Label1" runat="server" Text='<%# User.IsInRole("Administrators") %>'></asp:Label>

                </td>

            </tr>

            <tr>

                <td class="lcol">

                    Regular Users</td>

                <td class="rcol">

                    <asp:Label ID="Label2" runat="server" Text='<%# Roles.IsUserInRole("Regular Users") %>'></asp:Label>

                </td>

            </tr>

            <tr>

                <td class="lcol" style="border-bottom: black thin solid">

                    <span style="font-size: 10pt">Power Users</span></td>

                <td class="rcol" style="font-size: 10pt; border-bottom: black thin solid">

                    <asp:Label ID="Label3" runat="server" Text='<%# ((RolePrincipal)User).IsInRole("Power Users") %>'></asp:Label>

                </td>

            </tr>

        </table>

        <br />

        <a href="Add_Delete_UserRoles.aspx">点击此处管理角色的登录的用户。</a>

        <br />

        <br />

        <small>

            <div id="result_box" dir="ltr" style="">

                注:本范例网页,创建角色所谓的“管理员” , “一般用户”和“超级用户” 。</div>

        </small>

   

    </div>

    </form>

</body>

</html>

/administrators_role/Administrators_Page.aspx部分:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Administrators_Page.aspx.cs" Inherits="administrators_role_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <div id="result_box" dir="ltr" style="">

            如果您到达此页面,那么您的角色是管理员。

            <br />

            <br />

            从Web.config文件中可以看到与此相关的快速入门网站的&lt;location/&gt;锁定访问此网页。</div>

   

    </div>

    </form>

</body>

</html>

l         使用rolemamage对页面进行授权

还可以通过使用role mamage对指定角色的用户进行页面授权。通过在web.Cinfig里面进行配置。

4.       总结

l         认证与授权机制

l         使用用户管理控件

l         成员资格与角色管理

posted @ 2009-05-11 02:58  棋木空间  阅读(2375)  评论(11编辑  收藏  举报