一:web.config配製檔案
<authentication mode="Forms">
<forms name="HuiBao" loginUrl="logon.aspx" protection="All" timeout="60" path="/">
</forms>
</authentication>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
<location path="EditAccount.aspx">
<system.web>
<authorization>
<allow roles="Mean"/>
<deny users="*" />
</authorization>
</system.web>
</location>//這裡用限制某一目錄下的頁面或某一頁中可以訪問的角色,如果角色不對,自動導向到Logon.aspx頁面,很方便,但缺點是人性化不高,不能彈出提示,所以下面用在每個頁面的pageLoad事件裡判斷角色再轉向。
二:Logon.aspx頁面
//在使用者登入驗證完畢後調用此方法寫cookie,使用者名稱作cookie名,使用者角色 作為cookie的內容
private void setCook(string userName,string userRole)
{
HttpCookie hk;
FormsAuthenticationTicket Fat ;
Fat = new FormsAuthenticationTicket(1,userName,DateTime.Now,DateTime.Now.AddMinutes(30),false,userRole);
string hashTicket = FormsAuthentication.Encrypt(Fat);
hk = new HttpCookie(FormsAuthentication.FormsCookieName,hashTicket);
hk.Expires=Fat.Expiration;
HttpContext.Current.Response.Cookies.Add(hk);
}
此方法底下還有兩句,導到原請求頁面去的,但在第一次登入的時候會自動導到default.aspx頁面,所以取消了。
1string requestUrl = FormsAuthentication.GetRedirectUrl(FormsAuthentication.FormsCookieName,false);
2HttpContext.Current.Response.Redirect(requestUrl);
三:Global.asax頁面
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if(HttpContext.Current.User!=null) //驗證使用者不為空白
{
if(HttpContext.Current.User.Identity.IsAuthenticated)//是通過驗證了的
{
FormsIdentity fi = (FormsIdentity)HttpContext.Current.User.Identity; //Forms身分識別驗證
FormsAuthenticationTicket ticket = fi.Ticket; //取得票據
string userData = ticket.UserData; //取得資訊
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(fi,roles); //把角色資訊寫入目前使用者
}
}
}
四:在任意頁面中
private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置使用者代碼以初始化頁面
if(HttpContext.Current.User.IsInRole("Adminisrator"))
{
Response.Write("是這個角色");//做你想要的操作
}
else
{
//先彈出提示然後再導向到登入頁面。 如果不用提示,則前的的配製節就可以了0
Response.Write("<script language='javascript'>if(window.opener == null){alert('對不起,您無權訪問這個頁面,請登入')};location.href('Logon.aspx')</script>");
}
}
//登出
FormsAuthentication.SignOut();//登出
Response.Redirect("logon.aspx",true);