SQL Role manager, SQL Role provider SQL Authentication
To use a role store in SQL Server, add a connection string to point to your role database and add a role provider definition in the Web.config file, as shown here.
<configuration>
<connectionStrings>
<add name="SqlRoleManagerConnection"
connectionString="Data Source=sqlinstance;
Initial Catalog=aspnetdb;Integrated Security=SSPI;">
</add>
</connectionStrings>
</configuration>
<roleManager enabled="true" defaultProvider="SqlRoleManager">
<providers>
<add name="SqlRoleManager"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="SqlRoleManagerConnection"
applicationName="MyApplication" />
</providers>
</roleManager>
Using the Role Management APIs
You can assign users to roles or remove users from roles by using methods of the System.Web.Security.Roles class. You can also check for the user's role membership and authorize as appropriate.
Note Because the WindowsTokenRoleProvider is read-only, it supports only the IsUserInRole andGetRolesForUser methods.
The following code shows how to create new roles.
using System.Web.Security;
if (!Roles.RoleExists("TestRole"))
{
Roles.CreateRole("TestRole");
}
Note Role names are not case sensitive. If you attempt to create the same role twice, an exception is thrown.
The following code shows how to add uses to roles.
// Example 1 - Add one user to one role
Roles.AddUserToRole("TestOne", "ExampleRole1");
// Example 2 - Add one user to several roles
Roles.AddUserToRoles("TestTwo",
new string[] { "ExampleRole1", "ExampleRole2" });
// Example 3 - Add several users to one roles
Roles.AddUsersToRole(
new string[] { "TestTwo", "TestThree" }, "ExampleRole3");
// Example 4 - Add several users to several roles
Roles.AddUsersToRoles(
new string[] { "TestThree", "TestFour" },
new string[] { "ExampleRole4" });
The following code shows how to remove users from roles.
// Example 1 - Add one user to one role
Roles.RemoveUserFromRole("TestOne", "ExampleRole1");
// Example 2 - Add one user to several roles
Roles.RemoveUserFromRoles("TestTwo",
new string[] { "ExampleRole1", "ExampleRole2" });
// Example 3 - Add several users to one roles
Roles.RemoveUsersFromRole(
new string[] { "TestTwo", "TestThree" }, "ExampleRole3");
// Example 4 - Add several users to several roles
Roles.RemoveUsersFromRoles(
new string[] { "TestThree", "TestFour" },
new string[] { "ExampleRole4" });
Note Both the AddUser and RemoveUser methods throw a TargetInvocationException if you specify a role that does not exist or if you specify an invalid Windows user account name.
Sample: Using SqlRoleProvider or AuthorizationStoreRoleProvider
This sample uses the SqlRoleProvider or AuthorizationStoreRoleProvider.
To test role management with SqlRoleProvider or AuthorizationStoreRoleProvider
- Use Visual Studio.NET 2005 to create a Web site, add a Web.config file, and configure the role store andSqlRoleProvider or AuthorizationStoreRoleProvider as described in steps 1 and 2 of this How To.
- Using the Internet Information Services MMC snap-in, edit the properties of the Web site. Edit the Anonymous access and authentication control on the Directory security tab. Clear the Anonymous access check box and select the Integrated Windows authentication check box.
- In the Web.config file, enable Windows authentication.
<system.web>
...
<authentication mode="Windows"/>
...
</system.web>
- Add the following code to the Default.aspx file.
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Roles.RoleExists("TestRole"))
{
Roles.CreateRole("TestRole");
}
ShowRoleMembership();
}
private void ShowRoleMembership()
{
if (Roles.IsUserInRole("TestRole"))
{
Label1.Text = User.Identity.Name + " is in role TestRole";
}
else
{
Label1.Text = User.Identity.Name + " is NOT in role TestRole";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Roles.AddUserToRole(User.Identity.Name, "TestRole");
ShowRoleMembership();
}
protected void Button2_Click(object sender, EventArgs e)
{
Roles.RemoveUserFromRole(User.Identity.Name, "TestRole");
ShowRoleMembership();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Add to role"
OnClick="Button1_Click" /><br />
<br />
<asp:Button ID="Button2" runat="server" Text="Remove from role"
OnClick="Button2_Click" /><br />
<br />
<asp:Label ID="Label1" runat="server" />
</div>
</form>
</body>
</html>
- Run the application. Note the following features about this application:
- When you browse to the application, the code in the Page_Load event handler creates the role TestRole if it does not already exist.
- The text of Label1 shows whether the current authenticated user is a member of the TestRole role.
- When you click the Add to role button, the code in the Button1_Click event handler uses the role management API to add the current authenticated user to the TestRole role.
- If you click the Add to role button again before clicking the Remove from role button, the call toRoles.AddUserToRole throws an exception because the user is already in the role TestUser. You must code for this condition in your applications.
- When you click the Remove from role button, the current authenticated user is removed from the role TestRole.
- If you click the Remove from role button again before clicking the Add to role button, the call toRoles.RemoveUserFromRole throws an exception because the user is already not in the roleTestUser and cannot be removed twice. You must code for this condition in your applications.
To control access to pages and folders using roles
A typical use for roles is to establish rules that allow or deny access to pages or folders. You can set up such access rules in the <authorization> section of the Web.config file. The following example allows users in the role of members to view pages in the folder named memberPages and denies access to anyone else.
<configuration>
<location path="memberPages">
<system.web>
<authorization>
<allow roles="Manager" />
<deny users="*" />
</authorization>
</system.web>
</location>
<!-- other configuration settings here -->
<configuration>
ADDITIONAL CONSIDERATIONS
If a user's browser accepts cookies, you can store role information for that user in a cookie on the user's computer. On each page request, ASP.NET reads the role information for that user from the cookie. This can improve application performance by reducing the amount of communication required with the roles data store.
To configure and enable role caching, set cacheRolesInCookie = true as shown here.
<roleManager enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPXROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All"
defaultProvider="AspNetSqlRoleProvider"
createPersistentCookie="false"
maxCachedResults="25"/>
If the role information for a user is too long to store in a cookie, ASP.NET stores only the most recently used role information in the cookie, and then it looks up additional role information in the data source as required.
To secure the role cookie:
- Set cookieRequireSSL to true to ensure the cookie is only used over an SSL protected channel.
- Set createPersistentCookie to false to prevent the cookie from being stored on the client computer, in which case the cookie is only used to protect the current session.
- Set cookieTimeout to the number of minutes for which the cookie is valid.
No comments:
Post a Comment