asp.net Forms身分識別驗證和基於角色的許可權訪問

來源:互聯網
上載者:User

主要思想:Forms身分識別驗證用來判斷是否合法使用者,當使用者合法後,再通過使用者的角色決定能訪問的頁面。
具體步驟:
1、建立一個網站,結構如下:
網站根目錄
Admin目錄 ----> 管理員目錄
Manager.aspx ----> 管理員可以訪問的頁面
Users目錄 ----> 註冊使用者目錄
Welcome.aspx ----> 註冊使用者可以訪問的頁面
Error目錄 ----> 錯誤提示目錄
AccessError.htm ----> 訪問錯誤的提示頁面
default.aspx ----> 網站預設頁面
login.aspx ----> 網站登入頁面
web.config ----> 網站設定檔
2、配置web.config如下: 複製代碼 代碼如下: <configuration>
<system.web>
<!--設定Forms身分識別驗證-->
<authentication mode="Forms">
<forms loginUrl="Login.aspx" name="MyWebApp.APSXAUTH" path="/" protection="All" timeout="30"/>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</configuration>

<!--設定Admin目錄的存取權限-->
<location path="Admin">
<system.web>
<authorization>
<allow roles="Admin"/>
<deny users="?"/>
</authorization>
</system.web>
</location>
<!--設定Users目錄的存取權限-->
<location path="Users">
<system.web>
<authorization>
<allow roles="User"/>
<deny users="?"/>
</authorization>
</system.web>
</location>

3、在login.aspx頁面的登入部分代碼如下: 複製代碼 代碼如下: protected void btnLogin_Click(object sender, EventArgs e)
{
//Forms身分識別驗證初始化
FormsAuthentication.Initialize();
//驗證使用者輸入並得到登入使用者,txtName是使用者名稱稱,txtPassword是登入密碼
UserModel um = ValidUser(txtName.Text.Trim(),txtPassword.Text.Trim());
if (um != null)
{
//建立身分識別驗證票據
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
um.Name,
DateTime.Now,
DateTime.Now.AddMinutes(30),
true,
um.Roles,//使用者所屬的角色字串
FormsAuthentication.FormsCookiePath);
//加密身分識別驗證票據
string hash = FormsAuthentication.Encrypt(ticket);
//建立要發送到用戶端的cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
//把準備好的cookie加入到響應流中
Response.Cookies.Add(cookie);

//轉寄到請求的頁面
Response.Redirect(FormsAuthentication.GetRedirectUrl(um.Name,false));
}
else
{
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterStartupScript(this.GetType(), "error_tip", "alert('使用者名稱或密碼錯誤!身分識別驗證失敗!');", true);
}
}
//驗證使用者
private UserModel ValidUser(string name, string password)
{
return new UserService().Validate(name, password);
}

4、給網站添加處理常式Global.asax,其中通用身分識別驗證代碼如下: 複製代碼 代碼如下: //改造原來的User,給其添加一個使用者所屬的角色資料
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,加入使用者擁有的角色數組
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}

5、在Admin目錄中Manager.aspx頁面載入代碼如下: 複製代碼 代碼如下: protected void Page_Load(object sender, EventArgs e)
{
//判斷通過身分識別驗證的使用者是否有許可權訪問本頁面
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
//判斷通過身分識別驗證的使用者是否是Admin角色
if (!id.Ticket.UserData.Contains("Admin"))
{
//跳轉到存取權限不夠的錯誤提示頁面
Response.Redirect("~/Error/AccessError.htm", true);
}
}
//安全退出按鈕的代碼
protected void btnExit_Click(object sender, EventArgs e)
{
//登出票據
FormsAuthentication.SignOut();
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterStartupScript(this.GetType(), "exit_tip", "alert('您已經安全退出了!');", true);
}

6、在Users目錄中Welcome.aspx頁面載入代碼如下: 複製代碼 代碼如下: protected void Page_Load(object sender, EventArgs e)
{
//判斷通過身分識別驗證的使用者是否有許可權訪問本頁面
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
//判斷通過身分識別驗證的使用者是否是User角色
if (!id.Ticket.UserData.Contains("User"))
{
//跳轉到存取權限不夠的錯誤提示頁面
Response.Redirect("~/Error/AccessError.htm", true);
}
}
//安全退出按鈕的代碼
protected void btnExit_Click(object sender, EventArgs e)
{
//登出票據
FormsAuthentication.SignOut();
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterStartupScript(this.GetType(), "exit_tip", "alert('您已經安全退出了!');", true);
}

測試結果:
資料:
假設有3個使用者,如下:
------------------------------------------
使用者名稱 密碼 角色字串
------------------------------------------
sa sa Admin,User
admin admin Admin
user user User
------------------------------------------
測試:
如果使用admin登入,只能訪問Admin目錄的Manager.aspx頁面;
如果使用user登入,只能訪問Users目錄的Welcome.aspx頁面;
使用sa登入,既能訪問Admin目錄的Manager.aspx頁面,又能訪問Users目錄的Welcome.aspx頁面。
注意:測試時注意及時點擊安全退出按鈕,否則影響測試結果。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.