webconfig配置如下
<authentication mode="Forms" >
<forms name=".SecurityDemo" loginUrl="login.aspx">//.SecurityDemo為cookie名,
</forms>
</authentication>
<authorization>
<deny users="?"/> //拒絕所有匿名使用者
<allow roles="admins"/>//允許管理層級使用者訪問
</authorization>
<location path="admin.aspx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
登陸時的後置代碼 login.aspx
private void btnLoginBetter_Click(object sender, System.EventArgs e)
{
if (this.tbName.Text == "admin" && this.tbPass.Text == "admin")
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,this.tbName.Text,DateTime.Now,DateTime.Now.AddMinutes(30),this.PersistCookie.Checked,"User");
//建立一個驗證票據
string cookieStr = FormsAuthentication.Encrypt(ticket); //進行加密
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,cookieStr);//建立一個cookie,cookie名為web.config設定的名,值為加密後的資料cookieStr,
if (this.PersistCookie.Checked)//判斷使用者是否選中儲存cookie
cookie.Expires = ticket.Expiration;//擷取cookie到期時間
cookie.Path = FormsAuthentication.FormsCookiePath;//設定cookie儲存路徑
Response.Cookies.Add(cookie);
string strRedirect;
strRedirect = Request["ReturnUrl"];//取出返回url
if (strRedirect == null)
strRedirect = "Default.aspx";
Response.Redirect(strRedirect,true);
}
else
{
Response.Write("<script>alert('帳號或密碼錯誤!');self.location.href='02login.aspx'</script>");
}
}
通過驗證後的後置代碼 Default.aspx
private void Page_Load(object sender, System.EventArgs e)
{
this.lbUser.Text = User.Identity.Name;
if (User.IsInRole("Admin"))//判斷角色
this.lbSf.Text = "Admin";
else
this.lbSf.Text = "User";
}
private void btnLogout_Click(object sender, System.EventArgs e)
{
FormsAuthentication.SignOut();//登出票
Response.Redirect("login.aspx",true);返回login.aspx頁面
}