您的位置:首页 > 编程语言 > ASP

ASP.NET Forms 权限验证

2010-12-15 14:40 316 查看
ASP.NET 的Forms权限验证,就是通过 web.config配置来改变每个用户的不同文件夹访问权限。例如,A,B,C用户属于USERS组,配置A,B,C三个用户只能访问W目录下的页面。具体配置如下:

1) 建立站点根目录下web.config,authentication 节点的mode设置为Forms。

<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<authentication mode="Forms">
<forms name="test" protection="All" timeout="30" loginUrl="~/Login.aspx" defaultUrl="~/" slidingExpiration="true"/>
</authentication>
<compilation debug="true"/>
</system.web>
</configuration>

2) 站点目录下建立W文件夹,添加配置文件web.config,W文件夹下新建test.aspx页面。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<authorization>
<allow roles="USERS"/> <!--只要登录用户就可以访问roles="?"-->
<deny users="*"/>
</authorization>
</system.web>
</configuration>

3) 根目录下新建登录页面(login.aspx),登录按钮事件代码:

FormsAuthenticationTicket _ticket = new FormsAuthenticationTicket(0, "test", DateTime.Now, DateTime.Now.AddMinutes(20), false, "USERS");
string encryptedTicket = FormsAuthentication.Encrypt(_ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);
if (String.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
{
Response.Redirect(FormsAuthentication.DefaultUrl);
}
else
{
Response.Redirect(Request.QueryString["ReturnUrl"]);
}

4) 站点根目录新建global.asax,在文件中加入Application_AuthenticateRequest事件,该事件将在安全模块建立起当前用户的有效的身份时被触发。

void Application_AuthenticateRequest(object sender, EventArgs e)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception ex)
{
return;
}

string[] roles = authTicket.UserData.Split(new char[] { ',' });

FormsIdentity id = new FormsIdentity(authTicket);

System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, roles);
Context.User = principal;
}

当访问W目录下的test.aspx页面时就需要登录,当登录的用户属于USER组时,就有权限访问,否则无权限访问。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: