一直以来网站管理后台的验证代码都是自己在写,这两天学习了一下ASP.NET的基于FORMS认证的方式,只要统一配置就可以,不用每个管理页面都加入验证代码,非常方便实用.
举个例子:
网站结构包括:
Admin(目录)
+index.aspx
Default.aspx
Web.config
Global.asax
我们要多Web.config进行配置,实现管理员可以访问Admin目录,其他角色都不可以访问.
<authentication mode="Forms">
<forms loginUrl="default.aspx" protection="All" requireSSL="false"></forms>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
<forms loginUrl="default.aspx" protection="All" requireSSL="false"></forms>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
再对Admin目录设置访问权限.
<location path="admin">
<system.web>
<authorization>
<allow roles="managers"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<system.web>
<authorization>
<allow roles="managers"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
下面就是登录用户的代码了,这里有两段代码,一个是管理员登录,一个是普通用户登录
protected void Button1_Click(object sender, EventArgs e)
{
string role = "managers";
FormsAuthenticationTicket authTickets = new FormsAuthenticationTicket(1, "Lordz", DateTime.Now, DateTime.Now.AddYears(1), false, role);
string encryptedTicket = FormsAuthentication.Encrypt(authTickets);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authCookie.Expires = authTickets.Expiration;
HttpContext.Current.Response.Cookies.Add(authCookie);
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl = "admin/index.aspx";
Response.Redirect(returnUrl);
}
protected void Button2_Click(object sender, EventArgs e)
{
string role = "User";
FormsAuthenticationTicket authTickets = new FormsAuthenticationTicket(1, "Lordz", DateTime.Now, DateTime.Now.AddYears(1), false, role);
string encryptedTicket = FormsAuthentication.Encrypt(authTickets);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authCookie.Expires = authTickets.Expiration;
HttpContext.Current.Response.Cookies.Add(authCookie);
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl = "admin/index.aspx";
Response.Redirect(returnUrl);
}
{
string role = "managers";
FormsAuthenticationTicket authTickets = new FormsAuthenticationTicket(1, "Lordz", DateTime.Now, DateTime.Now.AddYears(1), false, role);
string encryptedTicket = FormsAuthentication.Encrypt(authTickets);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authCookie.Expires = authTickets.Expiration;
HttpContext.Current.Response.Cookies.Add(authCookie);
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl = "admin/index.aspx";
Response.Redirect(returnUrl);
}
protected void Button2_Click(object sender, EventArgs e)
{
string role = "User";
FormsAuthenticationTicket authTickets = new FormsAuthenticationTicket(1, "Lordz", DateTime.Now, DateTime.Now.AddYears(1), false, role);
string encryptedTicket = FormsAuthentication.Encrypt(authTickets);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authCookie.Expires = authTickets.Expiration;
HttpContext.Current.Response.Cookies.Add(authCookie);
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl = "admin/index.aspx";
Response.Redirect(returnUrl);
}
其实只有定义role这个变量的时候是不一样,其他地方代码都相同
注意:我上面的代码是为了方便测试,没有写对用户的验证,这个要大家自己根据实际情况来写了.
还有一个重要的地方,需要在Global.asax里添加如下代码
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (null == authCookie)
{
// There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception ex)
{
// Log exception details (omitted for simplicity)
return;
}
if (null == authTicket)
{
// Cookie failed to decrypt.
return;
}
// When the ticket was created, the UserData property was assigned a
// pipe delimited string of role names.
string[] roles = authTicket.UserData.Split(new char[] { '|' });
// Create an Identity object
FormsIdentity id = new FormsIdentity(authTicket);
// This principal will flow throughout the request.
System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, roles);
// Attach the new principal object to the current HttpContext object
Context.User = principal;
}
{
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (null == authCookie)
{
// There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception ex)
{
// Log exception details (omitted for simplicity)
return;
}
if (null == authTicket)
{
// Cookie failed to decrypt.
return;
}
// When the ticket was created, the UserData property was assigned a
// pipe delimited string of role names.
string[] roles = authTicket.UserData.Split(new char[] { '|' });
// Create an Identity object
FormsIdentity id = new FormsIdentity(authTicket);
// This principal will flow throughout the request.
System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, roles);
// Attach the new principal object to the current HttpContext object
Context.User = principal;
}
大家可以设置断点来看看上面代码是在上面时候被执行,目的是在用户得到认证以后赋予其角色,具体的解释网上面有很多,大家可以搜索一下,我也不是很明白为什么要这段,知道的朋友可以说一下,呵呵
附上代码/Files/lordz/WebSite1.rar
学习之用,高手勿笑.