asp.net Forms身份驗(yàn)證和基于角色的權(quán)限訪問(wèn)
更新時(shí)間:2009年09月25日 15:14:33 作者:
Forms身份驗(yàn)證用來(lái)判斷是否合法用戶,當(dāng)用戶合法后,再通過(guò)用戶的角色決定能訪問(wèn)的頁(yè)面。
主要思想:Forms身份驗(yàn)證用來(lái)判斷是否合法用戶,當(dāng)用戶合法后,再通過(guò)用戶的角色決定能訪問(wèn)的頁(yè)面。
具體步驟:
1、創(chuàng)建一個(gè)網(wǎng)站,結(jié)構(gòu)如下:
網(wǎng)站根目錄
Admin目錄 ----> 管理員目錄
Manager.aspx ----> 管理員可以訪問(wèn)的頁(yè)面
Users目錄 ----> 注冊(cè)用戶目錄
Welcome.aspx ----> 注冊(cè)用戶可以訪問(wèn)的頁(yè)面
Error目錄 ----> 錯(cuò)誤提示目錄
AccessError.htm ----> 訪問(wèn)錯(cuò)誤的提示頁(yè)面
default.aspx ----> 網(wǎng)站默認(rèn)頁(yè)面
login.aspx ----> 網(wǎng)站登錄頁(yè)面
web.config ----> 網(wǎng)站配置文件
2、配置web.config如下:
<configuration>
<system.web>
<!--設(shè)置Forms身份驗(yàn)證-->
<authentication mode="Forms">
<forms loginUrl="Login.aspx" name="MyWebApp.APSXAUTH" path="/" protection="All" timeout="30"/>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</configuration>
<!--設(shè)置Admin目錄的訪問(wèn)權(quán)限-->
<location path="Admin">
<system.web>
<authorization>
<allow roles="Admin"/>
<deny users="?"/>
</authorization>
</system.web>
</location>
<!--設(shè)置Users目錄的訪問(wèn)權(quán)限-->
<location path="Users">
<system.web>
<authorization>
<allow roles="User"/>
<deny users="?"/>
</authorization>
</system.web>
</location>
3、在login.aspx頁(yè)面的登錄部分代碼如下:
protected void btnLogin_Click(object sender, EventArgs e)
{
//Forms身份驗(yàn)證初始化
FormsAuthentication.Initialize();
//驗(yàn)證用戶輸入并得到登錄用戶,txtName是用戶名稱,txtPassword是登錄密碼
UserModel um = ValidUser(txtName.Text.Trim(),txtPassword.Text.Trim());
if (um != null)
{
//創(chuàng)建身份驗(yàn)證票據(jù)
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
um.Name,
DateTime.Now,
DateTime.Now.AddMinutes(30),
true,
um.Roles,//用戶所屬的角色字符串
FormsAuthentication.FormsCookiePath);
//加密身份驗(yàn)證票據(jù)
string hash = FormsAuthentication.Encrypt(ticket);
//創(chuàng)建要發(fā)送到客戶端的cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
//把準(zhǔn)備好的cookie加入到響應(yīng)流中
Response.Cookies.Add(cookie);
//轉(zhuǎn)發(fā)到請(qǐng)求的頁(yè)面
Response.Redirect(FormsAuthentication.GetRedirectUrl(um.Name,false));
}
else
{
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterStartupScript(this.GetType(), "error_tip", "alert('用戶名或密碼錯(cuò)誤!身份驗(yàn)證失敗!');", true);
}
}
//驗(yàn)證用戶
private UserModel ValidUser(string name, string password)
{
return new UserService().Validate(name, password);
}
4、給網(wǎng)站添加處理程序Global.asax,其中通用身份驗(yàn)證代碼如下:
//改造原來(lái)的User,給其添加一個(gè)用戶所屬的角色數(shù)據(jù)
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null )
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
string userData = ticket.UserData;
string[] roles = userData.Split(',');
//重建HttpContext.Current.User,加入用戶擁有的角色數(shù)組
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}
5、在Admin目錄中Manager.aspx頁(yè)面加載代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
//判斷通過(guò)身份驗(yàn)證的用戶是否有權(quán)限訪問(wèn)本頁(yè)面
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
//判斷通過(guò)身份驗(yàn)證的用戶是否是Admin角色
if (!id.Ticket.UserData.Contains("Admin"))
{
//跳轉(zhuǎn)到訪問(wèn)權(quán)限不夠的錯(cuò)誤提示頁(yè)面
Response.Redirect("~/Error/AccessError.htm", true);
}
}
//安全退出按鈕的代碼
protected void btnExit_Click(object sender, EventArgs e)
{
//注銷票據(jù)
FormsAuthentication.SignOut();
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterStartupScript(this.GetType(), "exit_tip", "alert('您已經(jīng)安全退出了!');", true);
}
6、在Users目錄中Welcome.aspx頁(yè)面加載代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
//判斷通過(guò)身份驗(yàn)證的用戶是否有權(quán)限訪問(wèn)本頁(yè)面
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
//判斷通過(guò)身份驗(yàn)證的用戶是否是User角色
if (!id.Ticket.UserData.Contains("User"))
{
//跳轉(zhuǎn)到訪問(wèn)權(quán)限不夠的錯(cuò)誤提示頁(yè)面
Response.Redirect("~/Error/AccessError.htm", true);
}
}
//安全退出按鈕的代碼
protected void btnExit_Click(object sender, EventArgs e)
{
//注銷票據(jù)
FormsAuthentication.SignOut();
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterStartupScript(this.GetType(), "exit_tip", "alert('您已經(jīng)安全退出了!');", true);
}
測(cè)試結(jié)果:
數(shù)據(jù):
假設(shè)有3個(gè)用戶,如下:
------------------------------------------
用戶名 密碼 角色字符串
------------------------------------------
sa sa Admin,User
admin admin Admin
user user User
------------------------------------------
測(cè)試:
如果使用admin登錄,只能訪問(wèn)Admin目錄的Manager.aspx頁(yè)面;
如果使用user登錄,只能訪問(wèn)Users目錄的Welcome.aspx頁(yè)面;
使用sa登錄,既能訪問(wèn)Admin目錄的Manager.aspx頁(yè)面,又能訪問(wèn)Users目錄的Welcome.aspx頁(yè)面。
注意:測(cè)試時(shí)注意及時(shí)點(diǎn)擊安全退出按鈕,否則影響測(cè)試結(jié)果。
具體步驟:
1、創(chuàng)建一個(gè)網(wǎng)站,結(jié)構(gòu)如下:
網(wǎng)站根目錄
Admin目錄 ----> 管理員目錄
Manager.aspx ----> 管理員可以訪問(wèn)的頁(yè)面
Users目錄 ----> 注冊(cè)用戶目錄
Welcome.aspx ----> 注冊(cè)用戶可以訪問(wèn)的頁(yè)面
Error目錄 ----> 錯(cuò)誤提示目錄
AccessError.htm ----> 訪問(wèn)錯(cuò)誤的提示頁(yè)面
default.aspx ----> 網(wǎng)站默認(rèn)頁(yè)面
login.aspx ----> 網(wǎng)站登錄頁(yè)面
web.config ----> 網(wǎng)站配置文件
2、配置web.config如下:
復(fù)制代碼 代碼如下:
<configuration>
<system.web>
<!--設(shè)置Forms身份驗(yàn)證-->
<authentication mode="Forms">
<forms loginUrl="Login.aspx" name="MyWebApp.APSXAUTH" path="/" protection="All" timeout="30"/>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</configuration>
<!--設(shè)置Admin目錄的訪問(wèn)權(quán)限-->
<location path="Admin">
<system.web>
<authorization>
<allow roles="Admin"/>
<deny users="?"/>
</authorization>
</system.web>
</location>
<!--設(shè)置Users目錄的訪問(wèn)權(quán)限-->
<location path="Users">
<system.web>
<authorization>
<allow roles="User"/>
<deny users="?"/>
</authorization>
</system.web>
</location>
3、在login.aspx頁(yè)面的登錄部分代碼如下:
復(fù)制代碼 代碼如下:
protected void btnLogin_Click(object sender, EventArgs e)
{
//Forms身份驗(yàn)證初始化
FormsAuthentication.Initialize();
//驗(yàn)證用戶輸入并得到登錄用戶,txtName是用戶名稱,txtPassword是登錄密碼
UserModel um = ValidUser(txtName.Text.Trim(),txtPassword.Text.Trim());
if (um != null)
{
//創(chuàng)建身份驗(yàn)證票據(jù)
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
um.Name,
DateTime.Now,
DateTime.Now.AddMinutes(30),
true,
um.Roles,//用戶所屬的角色字符串
FormsAuthentication.FormsCookiePath);
//加密身份驗(yàn)證票據(jù)
string hash = FormsAuthentication.Encrypt(ticket);
//創(chuàng)建要發(fā)送到客戶端的cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
//把準(zhǔn)備好的cookie加入到響應(yīng)流中
Response.Cookies.Add(cookie);
//轉(zhuǎn)發(fā)到請(qǐng)求的頁(yè)面
Response.Redirect(FormsAuthentication.GetRedirectUrl(um.Name,false));
}
else
{
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterStartupScript(this.GetType(), "error_tip", "alert('用戶名或密碼錯(cuò)誤!身份驗(yàn)證失敗!');", true);
}
}
//驗(yàn)證用戶
private UserModel ValidUser(string name, string password)
{
return new UserService().Validate(name, password);
}
4、給網(wǎng)站添加處理程序Global.asax,其中通用身份驗(yàn)證代碼如下:
復(fù)制代碼 代碼如下:
//改造原來(lái)的User,給其添加一個(gè)用戶所屬的角色數(shù)據(jù)
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null )
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
string userData = ticket.UserData;
string[] roles = userData.Split(',');
//重建HttpContext.Current.User,加入用戶擁有的角色數(shù)組
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}
5、在Admin目錄中Manager.aspx頁(yè)面加載代碼如下:
復(fù)制代碼 代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
//判斷通過(guò)身份驗(yàn)證的用戶是否有權(quán)限訪問(wèn)本頁(yè)面
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
//判斷通過(guò)身份驗(yàn)證的用戶是否是Admin角色
if (!id.Ticket.UserData.Contains("Admin"))
{
//跳轉(zhuǎn)到訪問(wèn)權(quán)限不夠的錯(cuò)誤提示頁(yè)面
Response.Redirect("~/Error/AccessError.htm", true);
}
}
//安全退出按鈕的代碼
protected void btnExit_Click(object sender, EventArgs e)
{
//注銷票據(jù)
FormsAuthentication.SignOut();
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterStartupScript(this.GetType(), "exit_tip", "alert('您已經(jīng)安全退出了!');", true);
}
6、在Users目錄中Welcome.aspx頁(yè)面加載代碼如下:
復(fù)制代碼 代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
//判斷通過(guò)身份驗(yàn)證的用戶是否有權(quán)限訪問(wèn)本頁(yè)面
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
//判斷通過(guò)身份驗(yàn)證的用戶是否是User角色
if (!id.Ticket.UserData.Contains("User"))
{
//跳轉(zhuǎn)到訪問(wèn)權(quán)限不夠的錯(cuò)誤提示頁(yè)面
Response.Redirect("~/Error/AccessError.htm", true);
}
}
//安全退出按鈕的代碼
protected void btnExit_Click(object sender, EventArgs e)
{
//注銷票據(jù)
FormsAuthentication.SignOut();
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterStartupScript(this.GetType(), "exit_tip", "alert('您已經(jīng)安全退出了!');", true);
}
測(cè)試結(jié)果:
數(shù)據(jù):
假設(shè)有3個(gè)用戶,如下:
------------------------------------------
用戶名 密碼 角色字符串
------------------------------------------
sa sa Admin,User
admin admin Admin
user user User
------------------------------------------
測(cè)試:
如果使用admin登錄,只能訪問(wèn)Admin目錄的Manager.aspx頁(yè)面;
如果使用user登錄,只能訪問(wèn)Users目錄的Welcome.aspx頁(yè)面;
使用sa登錄,既能訪問(wèn)Admin目錄的Manager.aspx頁(yè)面,又能訪問(wèn)Users目錄的Welcome.aspx頁(yè)面。
注意:測(cè)試時(shí)注意及時(shí)點(diǎn)擊安全退出按鈕,否則影響測(cè)試結(jié)果。
您可能感興趣的文章:
- 淺談asp.net Forms身份驗(yàn)證詳解
- 詳解ASP.NET MVC Form表單驗(yàn)證
- 關(guān)于C#.net winform程序驗(yàn)證moss的集成身份認(rèn)證實(shí)例
- Asp.Net二級(jí)域名共享Forms身份驗(yàn)證、下載站/圖片站的授權(quán)訪問(wèn)控制
- ASP.NET Internet安全Forms身份驗(yàn)證方法
- asp.net forms身份驗(yàn)證,避免重復(fù)造輪子
- asp.net 基于forms驗(yàn)證的目錄角色權(quán)限的實(shí)現(xiàn)
- asp.net 特定目錄form驗(yàn)證
- ASP.net Forms驗(yàn)證Demo
- .net MVC使用IPrincipal進(jìn)行Form登錄即權(quán)限驗(yàn)證(3)
相關(guān)文章
asp.net下 jquery jason 高效傳輸數(shù)據(jù)
jquery jason 高效傳輸數(shù)據(jù)轉(zhuǎn)自網(wǎng)上稍有修改2009-03-03ASP.NET GridView 實(shí)現(xiàn)課程表顯示(動(dòng)態(tài)合并單元格)實(shí)現(xiàn)步驟
GridView,ASP.NET中很常用的數(shù)據(jù)顯示控件,這里,我將用這個(gè)控件來(lái)實(shí)現(xiàn)課程表的顯示。首先說(shuō)說(shuō)課程表的顯示與普通記錄的顯示有何不同?感興趣的朋友可以了解下,或許對(duì)你有所幫助2013-02-02ASP.NET中DES加密與解密MD5加密幫助類的實(shí)現(xiàn)代碼
這篇文章主要介紹了ASP.NET中DES加密與解密MD5加密幫助類的實(shí)例代碼,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-07-07Asp.net使用HttpModule壓縮并刪除空白Html請(qǐng)求的實(shí)現(xiàn)代碼
當(dāng)我們壓縮我的Response后再傳到Client端時(shí),可以明顯節(jié)省寬帶. 提升Site的性能. 現(xiàn)在的瀏覽器大部分都支持Gzip,Deflate壓縮2011-11-11用Jquery訪問(wèn)WebService并返回Json的代碼
經(jīng)常會(huì)用JavaScript訪問(wèn)asp.net的Webservice的需求,通常的方法是用asp.net ajax來(lái)解決,但asp.net ajax框架在不國(guó)內(nèi)并不經(jīng)常被使用。2008-09-09asp.net實(shí)現(xiàn)生成縮略圖及給原始圖加水印的方法示例
這篇文章主要介紹了asp.net實(shí)現(xiàn)生成縮略圖及給原始圖加水印的方法,結(jié)合具體實(shí)例形式分析了asp.net圖片的縮略圖與水印操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-10-10.net6?使用Senparc開發(fā)小程序配置過(guò)程
這篇文章主要介紹了.net6?使用Senparc開發(fā)小程序配置,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07