建立角色和映射用户
用户到角色的映射可以存储在 Active Directory、SQL Server 表等数据存储区中。余下的步骤假定角色是从 SQL Server 数据库中提取的。
在运行时分配角色
当用户登录时,应用程序从数据库或目录服务中查找角色。然后将角色放置在 FormsAuthenticationTicket 中以避免后面对数据存储区的请求,从而提高性能。角色分配在以下代码中进行演示,这可在成功进行身份验证之后,在登录页后面的代码中实现。角色是一个帮助器类(在此未显示),当调用构造函数时,它从角色数据库中提取角色并将它们放置到内部角色数组中。由于我们正在身份验证票中将角色存储为字符串,因此类的 ToString 方法将数组转换为字符串表示形式。在此示例中,角色帮助器类接受三个参数:已验证身份的用户、应用程序名称和到包含角色的数据库的连接字符串。
HttpContext currentContext = HttpContext.Current;
string formsCookieStr = string.Empty;
Roles userRoles = new Roles(UserId,SFConfig.ApplicationName,SFConfig.RoleDBConnString);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // version
UserId, // user name
DateTime.Now, // issue time
DateTime.Now.AddMinutes(30), // expires
false, // persistent
userRoles.ToString() // user data
);
// get the encrypted representation suitable for placing in a HTTP cookie
formsCookieStr = FormsAuthentication.Encrypt(ticket);
HttpCookie FormsCookie = new HttpCookie(FormsAuthentication.FormsCookieName, formsCookieStr);
currentContext.Response.Cookies.Add(FormsCookie);
用户后面提交的请求将在请求标题中包含身份验证票,而服务器上的运行库将基于已登录用户的详细信息创建身份和用户。然而,并不会自动提取和分配添加到身份验证票的角色。要使用适当的用户角色设置用户,需要在下面的步骤中描述的运行线程上创建一个新用户并进行替换。
用户替换
用户对象表示代码所运行的安全上下文。实现基于角色的安全性的应用程序将基于与用户对象关联的角色来授予权限。若要设置每次请求时与用户关联的角色,在此实现中,应在 Global.asax 的 Application_OnAuthenticationRequest 函数中替换用户,如下所示:
protected void Application_OnAuthenticateRequest(Object src, EventArgs e)
{
HttpContext currentContext = HttpContext.Current;
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if( HttpContext.Current.User.Identity is FormsIdentity )
{
FormsIdentity id = HttpContext.Current.User.Identity as FormsIdentity;
FormsAuthenticationTicket ticket = id.Ticket;
string userData = ticket.UserData;
// Roles is a helper class which places the roles of the
// currently logged on user into a string array
// accessable via the value property.
Roles userRoles = new Roles(userData);
HttpContext.Current.User = new GenericPrincipal(id, userRoles.Value);
}
}
}
}
检查角色成员
现在用户的角色已在线程的当前用户中可用,代码可以使用此角色信息来允许或拒绝对某些功能的访问。这可以通过以下的三种方式之一来实现:
代码的属性。
[PrincipalPermissionAttribute(SecurityAction.Demand, Role = "MyRole")]
IsInRole 方法调用
使用用户的 IsInRole 方法以编程方式评估角色成员。
Web.Config
修改 Web.Config 文件,根据角色成员关系允许或拒绝对页的访问,如下所示:
<authorization>
<allow users="comma-separated list of users"
roles="comma-separated list of roles"
verbs="comma-separated list of verbs" />
<deny users="comma-separated list of users"
roles="comma-separated list of roles"
verbs="comma-separated list of verbs" />
</authorization>