<?xml version="1.0"?>
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="~/Login.aspx" defaultUrl="~/Default.aspx" path="/" timeout="30" protection="All" cookieless="UseDeviceProfile">
</forms>
</authentication>
<location path="Product.aspx">
<system.web>
<authorization>
<allow roles="Admin,Test"/>
<deny users="*" />
</authorization>
</system.web>
</location>
</configuration>
1.mode="Forms":表示採用Forms验证。
2.name:生成Cookie名稱,
3.loginUrl:對未經驗証的Url將轉到此登錄頁
4.path:Cookie路徑,如在生成的Cookie時未指定Path則用此默認Path.
5.timeout:Cookie的有效期.
6.以下說明了Product.aspx頁的隻有Admin,Test角色的用戶可訪問,其它用戶都拒絕訪問
<location path="Product.aspx">
<system.web>
<authorization>
<allow roles="Admin,Test"/>
<deny users="*" />
</authorization>
</system.web>
</location>
7
在Login.aspx頁登錄:
protected void btnLogin_Click(object sender, EventArgs e)
{
LZBWebSevice.Service websv = new LZBWebSevice.Service();//此為一WebSeviece
string strRoles = websv.Roles(this.txtUser.Text);//返回此用戶的Roles,可在數據庫中或XML中取
if (websv.Login(this.txtUser.Text))//判登錄是否成功
{
FormsAuthenticationTicket Tick = new FormsAuthenticationTicket //若成功則成生身份証票(1,FormsAuthentication.FormsCookieName, DateTime.Now, DateTime.Now.AddMinutes(1), false, strRoles,FormsAuthentication.FormsCookiePath);
string strCookie = FormsAuthentication.Encrypt(Tick);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strCookie);
Context.Response.Cookies.Add(cookie); //加入到Cookie中
if((Request["ReturnUrl"]!=null)
{
Context.Response.Redirect(Request["ReturnUrl"]); //指向需請求的Rul
}
else
{
Context.Response.Redirect(FormsAuthentication.DefaultUrl);
}
}
8.登錄後,需將用戶生成的Cookie恢復到Server端,在Global.axpx事件Application_PostAuthenticateRequest中寫:
protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authcookie = HttpContext.Current.Request.Cookies[cookieName];
if (null == authcookie)
{
return;
}
FormsAuthenticationTicket ticek = FormsAuthentication.Decrypt(authcookie.Value);
if (null == ticek)
{
}
string[] roles = ticek.UserData.Split(',');
FormsIdentity id = new FormsIdentity(ticek);
System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, roles);
HttpContext.Current.User = principal;
if (!HttpContext.Current.User.IsInRole("Admin"))
{
Response.Expires = 0;
}
}
浙公网安备 33010602011771号