//登入按鈕單擊事件
protected void btnLogin_Click(object sender, EventArgs e) { //擷取介面的值 string UserName = txtUserName.Text;//使用者名稱 string Password = txtPassword.Text;//密碼 string checkcode = Session["Code"].ToString();//從session中取出驗證碼 string code = txtCheckCode.Text;//擷取輸入的驗證碼 try { if (code != checkcode) { ClientScript.RegisterStartupScript(this.GetType(), "", "alert('驗證碼錯誤!')", true); return; } else { if (UserInfoLogic.checkUser(UserName, Password))//調用方法查詢使用者是否存在 { Session["login_name"] = txtUserName.Text;//將使用者名稱存入Session FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, UserName, DateTime.Now, DateTime.Now.AddMinutes(20), true, ""); string encryptTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket); Response.Cookies.Add(cookie); if (Request.QueryString["ReturnUrl"] == null) { Response.Redirect("Home.aspx");//登入成功跳轉到主介面 } else { Response.Redirect(Request.QueryString["ReturnUrl"]); } } else { //登入失敗跳轉到登入頁面 ClientScript.RegisterStartupScript(this.GetType(), "", "alert('登入失敗!')", true); Response.Redirect("Login.aspx"); } } } catch (Exception) { } }
web.config中配置代碼
<authentication mode="Forms"> <forms loginUrl="Login.aspx" name=".ASPXAUTH"></forms> <!--指定如果找不到任何有效身分識別驗證 Cookie,將請求重新導向到的用於登入的 URL。--> </authentication> <authorization> <deny users="?"></deny> <!--向授權規則映射添加一條拒絕對資源的訪問的授權規則。--> <!--<allow users="?" /> 向授權規則映射添加一個規則,該規則允許對資源進行訪問。--></authorization>
建立一個Global.asax
protected void Application_AuthenticateRequest(object sender, EventArgs e) { string cookieName = FormsAuthentication.FormsCookieName;//從驗證票據擷取Cookie的名字。 HttpCookie authCookie = Context.Request.Cookies[cookieName]; if (null == authCookie) { return; } //擷取驗證票據。 FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket == null) { return; } string[] roles = authTicket.UserData.Split(new char[] { ',' }); FormsIdentity id = new FormsIdentity(authTicket); System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, roles);//把產生的驗證票資訊和角色資訊賦給目前使用者. Context.User = principal; }