使用authentication進行身份驗證,與Forms表單登陸


做到登錄時,不像在用自己的邏輯去判斷用戶是否登陸,就上網搜查,得知還有此方法,這個方法用起來很簡單實用,第一次使用,還有很多不理解的地方,記下來方便以后查閱更改.

使用這個方法當然需要了解里面的屬性和用法,網上有很多了,可以自己搜索,我就主要貼出實現代碼

1.在web.config里的<system.web>節點添加

 /*loginurl 登陸界面如果沒有登錄則跳轉到次界面
 *name:cookie名稱,可以自己修改
 *defaultUrl:默認的頁面,登陸成功自動跳轉到默認界面
 *timeOut:cookie保留時間
 */ 
<authentication mode="Forms">    
      <forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH" defaultUrl="Index.aspx"  timeout="600" ></forms>
   </authentication>
//這個節點允許所有用戶訪問
   <authorization>
       <allow users="*" />
    </authorization>
 <!--//這個頁面節點允許任何人訪問-->//設置單個頁面的權限
  <location path="User_ForgotPass.aspx">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>

 

2.登錄界面判斷登陸成功使用FormsAuthentication.RedirectFromLoginPage方法

    string txtMail = Request["txt_mail"];
                string Com_Pwd = Request["txt_pwd"];
                DataTable msg = ComLogin(txtMail, Com_Pwd, true);
                if (msg.Rows.Count > 0)
                {
                    Session["name"] = msg.Rows[0][4];
                    Session["gs"] = msg.Rows[0][0];
                    //選中自動登錄
                    if (chkbox2.Checked)
                    {
              //選中自動登錄則第二個參數為true,保留cookie,cookie的持續時間與web.config中的timeout時間一樣 FormsAuthentication.RedirectFromLoginPage(txtMail,
true); } else { FormsAuthentication.RedirectFromLoginPage(txtMail,false); } } else { Response.Write("<script>alert('請檢查輸入的信息')</script>"); }

還有兩種方法,同樣可是實現該效果

    FormsAuthentication.SetAuthCookie(txtMail,false);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
    username,
    DateTime.Now,
    DateTime.Now.AddMinutes(720),
    isPersistent,
    userData,
    FormsAuthentication.FormsCookiePath);
 
// 加密票證
string encTicket = FormsAuthentication.Encrypt(ticket);
 
// 創建cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
HttpContext.Current.Response.Cookies.Add(cookie);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM