Asp.net身分識別驗證和授權
身分識別驗證是確定使用者身份的過程.在使用者通過了身分識別驗證後,開發人員就可以確定該使用者是否有權繼續操作.如果沒有進行身分識別驗證,就不能進行實體的授權.
授權是確定已驗證使用者是否有權訪問應用程式中的某個部分,某個點,或只能訪問應用程式提供的特定資料集.對使用者和組進行身分識別驗證和授權後,就可以根據使用者類型或配置定製網站.
asp.net身分識別驗證方式:
1.基本驗證
2.摘要身分識別驗證
3.表單身分識別驗證
4.Passport身分識別驗證
5.整合的Windows驗證
還可以開發自己的驗證方法.
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
...
</system.web>
可用的選項
<authentication mode="Windows|Forms|Passport|None">
Forms:未通過驗證的請求使用HTTP用戶端重新導向到一個HTML表單上.使用者要提供登入資訊,並提交表單.
如果應用程式驗證該請求,系統就發送一個表單,該表單包含重新獲得身份的認證或密鑰.
protected void Application_AuthenticateRequest(object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; HttpContext context = app.Context; //擷取本次Http請求的HttpContext對象 if (context.Request.IsAuthenticated) //驗證過的一般使用者才能進行角色驗證 { FormsIdentity Id = (FormsIdentity)context.User.Identity; //目前使用者標識 FormsAuthenticationTicket Ticket = Id.Ticket; //取得身份證票 string[] Roles = Ticket.UserData.Split(','); //將角色資料轉成字串數組,得到相關的角色資訊 context.User = new System.Security.Principal.GenericPrincipal(Id, Roles); //重建帶有角色資訊的使用者 } } string userId = "xx"; string pa = "123"; string roles = "Administrator"; //從其他地方取得使用者角色資料 FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, userId, DateTime.Now, DateTime.Now.AddMinutes(30), true, roles); //建立身分識別驗證票對象 string HashTicket = FormsAuthentication.Encrypt(Ticket); //加密序列化驗證票為字串 HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket); //產生Cookie Context.Response.Cookies.Add(UserCookie); //票據寫入Cookie Response.Redirect("Info.aspx");
if (this.UserName.Text == "xx" && this.Password.Text == "00") { FormsAuthentication.RedirectFromLoginPage(this.UserName.Text, true); } else this.FailureText.Text = "使用者名稱或密碼錯誤";