ASP.NET Forms 权限验证
时间:2010-12-15 来源:pirlo
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组时,就有权限访问,否则无权限访问。
相关阅读 更多 +
排行榜 更多 +