ASP.NET Tutorial/Authentication Authorization/Role

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Adding roles to the application

<%@ Page Language="C#" %>
<script runat="server">
   protected void Page_Load(object sender, EventArgs e)
   {
      ListBoxDataBind();
   }
   protected void Button1_Click(object sender, EventArgs e)
   {
      Roles.CreateRole(TextBox1.Text.ToString());
      ListBoxDataBind();
   }
   protected void ListBoxDataBind()
   {
      ListBox1.DataSource = Roles.GetAllRoles();
      ListBox1.DataBind();
   }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Role Manager</title>
</head>
<body>
    <form id="form1" runat="server">
        <h1>Role Manager</h1>
        Add Role:<br />
        <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
        <asp:Button ID="Button1" Runat="server" Text="Add Role to Application" 
            OnClick="Button1_Click" />
        Roles Defined:<br />
        <asp:ListBox ID="ListBox1" Runat="server">
        </asp:ListBox>
    </form>
</body>
</html>


Assigning a new user to a role.

File: Web.Config
<configuration>
    <system.web>
      <authorization>
        <allow roles="Managers"/>
        <deny users="*"/>
      </authorization>
    </system.web>
</configuration>


Configuring the WindowsTokenRoleProvider

When you use the WindowsTokenRoleProvider, roles correspond to Microsoft Windows groups. 
File: Web.Config
<configuration>
    <system.web>
      <authentication mode="Windows" />
      <roleManager enabled="true" defaultProvider="MyRoleProvider">
        <providers>
          <add
            name="MyRoleProvider"
            type="System.Web.Security.WindowsTokenRoleProvider" />
        </providers>
      </roleManager>
    </system.web>
</configuration>


Displaying a user"s roles.

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load()
    {
        if (!Request.IsAuthenticated)
        {
            FormsAuthentication.RedirectToLoginPage();
            Response.End();
        }
        if (!Roles.RoleExists("Managers"))
            Roles.CreateRole("Managers");
        if (!Roles.RoleExists("Sales"))
            Roles.CreateRole("Sales");
        if (!Roles.IsUserInRole("Managers"))
            Roles.AddUserToRole(User.Identity.Name, "Managers");
        if (!Roles.IsUserInRole("Sales"))
            Roles.AddUserToRole(User.Identity.Name, "Sales");
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Roles</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Your Roles</h1>
    <asp:GridView
        id="grdRoles"
        DataSourceID="srcRoles"
        EmptyDataText="You are not a member of any roles"
        GridLines="none"
        Runat="server" />
    <asp:ObjectDataSource
        id="srcRoles"
        TypeName="System.Web.Security.Roles"
        SelectMethod="GetRolesForUser"
        Runat="server" />
    </div>
    </form>
</body>
</html>


Displaying different content to members of the Windows Administrators group.

<%@ Page Language="C#" %>
<!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 id="Head1" runat="server">
    <title>Show Windows Roles</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:LoginView
        id="LoginView1"
        Runat="server">
        <RoleGroups>
        <asp:RoleGroup Roles="BUILTIN\Administrators">
            <ContentTemplate>
            <h1>Welcome Administrator!</h1>
            </ContentTemplate>
        </asp:RoleGroup>
        </RoleGroups>
        <LoggedInTemplate>
            <h1>Welcome Average User!</h1>
        </LoggedInTemplate>
    </asp:LoginView>
    </div>
    </form>
</body>
</html>


Enables the SqlRoleProvider.

The Role Manager is disabled by default. 
File: Web.Config
<configuration>
    <system.web>
        <roleManager enabled="true" />
        <authentication mode="Forms" />
    </system.web>
</configuration>


Getting all the roles of a specific user

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
   GridView1.DataSource = Roles.GetRolesForUser("userName")
   GridView1.DataBind()
End Sub


Looking up users in a particular role

<%@ Page Language="C#" %>
<script runat="server">
   protected void Page_Load(object sender, EventArgs e)
   {
      DropDownDataBind();
   }
   protected void Button1_Click(object sender, EventArgs e)
   {
      GridView1.DataSource = Roles.GetUsersInRole(DropDownList1.SelectedValue);
      GridView1.DataBind();
      DropDownDataBind();
   }
   protected void DropDownDataBind()
   {
      DropDownList1.DataSource = Roles.GetAllRoles();
      DropDownList1.DataBind();
   }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Role Manager</title>
</head>
<body>
    <form id="form1" runat="server">
        Roles:
        <asp:DropDownList ID="DropDownList1" Runat="server">
        </asp:DropDownList>
        <asp:Button ID="Button1" Runat="server" Text="Get Users In Role" 
         OnClick="Button1_Click" />
        <br />
        <br />
        <asp:GridView ID="GridView1" Runat="server">
        </asp:GridView>
    </form>
</body>
</html>


Windows roles

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="LabelPrincipalInfo" runat="server" />
    </div>
    </form>
</body>
</html>
File: Web.config
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.ru/.NetConfiguration/v2.0">
    <system.web>
        <compilation debug="true"/>
        <authentication mode="Windows"/>
        <authorization>
            <deny users="?" />
        </authorization>
        <roleManager enabled="true"
                     cacheRolesInCookie="false"
                     defaultProvider="WindowsRoles">
            <providers>
                <add name="WindowsRoles"
                     type="System.Web.Security.WindowsTokenRoleProvider" />
            </providers>
        </roleManager>
    </system.web>
</configuration>
File: Default.aspx.cs

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.Text;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if ((User != null) && (User.Identity.IsAuthenticated))
        {
            RolePrincipal rp = (RolePrincipal)User;
            StringBuilder Info = new StringBuilder();
            Info.AppendFormat("<h2>Welcome {0}!</h2>", User.Identity.Name);
            Info.AppendFormat("<b>Provider: </b>{0}<br>", rp.ProviderName);
            Info.AppendFormat("<b>Version: </b>{0}<br>", rp.Version);
            Info.AppendFormat("<b>Expiration: </b>{0}<br>", rp.ExpireDate);
            Info.AppendFormat("<b>Roles: </b><br>");
            string[] Roles = rp.GetRoles();
            foreach (string role in Roles)
            {
                if (!role.Equals(string.Empty))
                    Info.AppendFormat("-) {0}<br>", role);
            }
            LabelPrincipalInfo.Text = Info.ToString();
        }
    }
}