通过Forms验证进行角色管理
向进行身份验证的用户分配角色
由于窗体用户通常不是 Microsoft Windows 用户,因此默认情况下,窗体用户没有任何与之相关联的角色。因此,必须将进行身份验证的用户的角色附加到该用户的身份标识中,以便在代码内实现基于角色的安全性。
使用本节中的示例代码可在您的应用程序中实现基于角色的安全性。此示例代码将预先指定的角色分配给进行身份验证的用户。根据您存储用户数据的方式,您可实现自己的方法以检索通过身份验证的用户的角色,并将这些角色附加到身份验证用户的标识中,下面的代码示例显示了这一过程。
将以下代码复制到现有应用程序的 Global.asax 文件中,以将这些角色分配给 Application_AuthenticateRequest 事件处理程序中进行身份验证的用户:
public void Application_AuthenticateRequest( Object src , EventArgs e )
{
if (!(HttpContext.Current.User == null))
{
if (HttpContext.Current.User.Identity.AuthenticationType == "Forms" )
{
System.Web.Security.FormsIdentity id;
id = (System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity;
String[] myRoles = new String[2];
myRoles[0] = "Manager";
myRoles[1] = "Admin";
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id,myRoles);
}
}
}
在 .ASPX 页中检查用户角色并实现程序逻辑
下面的步骤演示了如何基于进行身份验证的用户所属的角色实现和控制程序逻辑。
1.
创建一个名为 Sample.aspx 的新 .aspx 页,然后粘贴以下代码:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web" %>
<script runat=server>
public void Page_Load() {
if (User.IsInRole("Admin")){
Response.Write ("You are an Administrator");}
else {
Response.Write ("You do not have any role assigned");}
}
</script>

浙公网安备 33010602011771号