2016-10-03 58 views
0

工作,我想使基於餅乾登錄系統(不是唱出來的頁面關閉或刷新時)登錄使用cookie是不是在ASP.net

這是爲Login.aspx後面的代碼。 cs:

string cmdText = "SELECT Username,Role FROM Login WHERE Username = '" + TextBox1.Text + "' AND Password = '" + TextBox2.Text + "'"; 

     string username = ""; 
     string role = ""; 
     using (SqlCommand SelectCommand = new SqlCommand(cmdText, connectionstring)) 
     { 
      SqlDataReader myReader; 
      connectionstring.Open(); 
      myReader = SelectCommand.ExecuteReader(); 


      while (myReader.Read()) 
      { 
       username = myReader["username"].ToString(); 
       role = myReader["role"].ToString(); 
      } 

      myReader.Close(); 

      if (!string.IsNullOrEmpty(username)) 
      { 
       string script = "alert(\"Login successful!\");"; 
       ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true); 
       connectionstring.Close(); 

       //STORE userinfo into cookie,set cookie Expires 1 day more 
       Response.Cookies["username"].Path = username; 
       Response.Cookies["username"].Expires = DateTime.Now.AddDays(1); 
       Response.Cookies["username"].Path = "/"; 

       Response.Cookies["role"].Path = role; 
       Response.Cookies["role"].Expires = DateTime.Now.AddDays(1); 
       Response.Cookies["role"].Path = "/"; 



       if (role.Equals("admin")) 
       { 
        Response.Redirect("admin.aspx"); 

        Label1.Text = "admin"; 

       } 

       if (role.Equals("doctor")) 
       { 
        Response.Redirect("doctor.aspx"); 
        Label1.Text = "doc"; 
       } 


       if (role.equals("patient")) 
       { 
        Response.Redirect("patient.aspx"); 
       } 

      } 
      else 
      { 
       string script = "alert(\"Login Failed!\");"; 
       ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true); 
       connectionstring.Close(); 
      } 
     } 
    } 

但看起來像我在重定向到我想要的頁面有問題。 當我輸入管理員角色的用戶名和密碼。它說,登錄成功,但沒有進入管理頁面。 這是爲什麼?我錯過了什麼嗎?

對於管理員(和其他網頁)我用這個代碼讀取餅乾

  string role = ""; 
      string username = ""; 
      if (Request.Cookies["role"] != null) 
      { 
        role = Request.Cookies["role"].Value; 

      } 

      if (Request.Cookies["role"] != null) 
      { 
       username = Request.Cookies["username"].Value; 
      } 

      if (role == "patient ") 
      { 
       //SET control visible=false if no right. 
       Button1.Visible = false; 
      } 

,這給登錄後修改cookies和/或用戶喊了一聲

//create cookie 
Response.Cookies["username"].Value = Server.UrlEncode("abc"); 
Response.Cookies["username"].Expires = DateTime.Now.AddDays(1); 
Response.Cookies["username"].Path = "/"; 

//modify cookie value 
Response.Cookies["username"].Value = Server.UrlEncode("def");; 
Response.Cookies["username"].Expires = DateTime.Now.AddDays(1); 
Response.Cookies["username"].Path = "/"; 


//delete cookie value 
//delete cookie infact is set Expires is past day DateTime.Now.AddDays(-1); 
Response.Cookies["username"].Value = Server.UrlEncode("def"); 
Response.Cookies["username"].Expires = DateTime.Now.AddDays(-1); 
Response.Cookies["username"].Path = "/"; 

//checking if cookie exist and reading it. 
if (Request.Cookies["role"] != null) 
       { 
         role = Server.UrlDecode(Request.Cookies["role"].Value); 

    } 

但照顧就像我錯過了一些我不瞭解的東西。我認爲問題是如果功能,在這裏:

if (role.Equals("admin")) 

有什麼建議嗎?這是使用cookie的正確方法嗎?

+3

爲什麼重新發明車輪? asp.net已經內置了所有這些功能。由於您的代碼現在非常容易受到SQL注入的影響,您的Cookie可能不安全。 Google'asp net authentication'或者閱讀這篇文章:http://www.c-sharpcorner.com/uploadfile/syedshakeer/formsauthentication-in-Asp-Net/ – VDWWD

+0

你是否收到response.redirect的錯誤信息? – Balaji

+0

@Balaji我無法重新連接到我想要的頁面。根據角色(醫生),我沒有被重定向到任何頁面。它只是呆在那裏,在登錄頁面。 – berg96

回答

0

爲什麼重新發明車輪? asp.net已經內置了所有這些功能。由於您的代碼現在非常容易受到SQL注入的影響,您的Cookie可能不安全。谷歌asp net authentication

這個簡單的教程可以告訴你如何開始:http://www.c-sharpcorner.com/uploadfile/syedshakeer/formsauthentication-in-Asp-Net/

您還需要爲存儲用戶創建一個數據庫,密碼,角色等,這篇文章可以幫你:https://www.asp.net/web-forms/overview/older-versions-security/membership/creating-the-membership-schema-in-sql-server-vb

此外,如果您在Visual Studio中創建一個新項目,它將添加一個登錄表單(以及更多),以便您可以使用該表單作爲示例。文件>新建項目> Web> ASP.NET Web應用程序

0

林種新的Cookie也不過一派幾個小時,即時通訊使用cookie這種方式,其工作後,希望它可以幫助你
添加餅乾:

string UserData = _User + "/" + _Password; 
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1 , _User , DateTime.Now, DateTime.Now.AddMinutes(60), _KeepLoggedIn, UserData); 
string encrypted = FormsAuthentication.Encrypt(ticket); 
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); 
cookie.Name = "SESSION"; 

Response.Cookies.Add(cookie); 

閱讀餅乾:

HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("SESSION"); 
      if (cookie != null) 
      { 
       FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); 
       var userName = ticket.Name; 
       var userData = ticket.UserData.Split('/').ToArray(); 

       string _User = userData[0]; 
       string _Password = userData[1]; 
       ... Your code to authenticate and 'Response.Redirect'... 
      } 

要 '刪除' 餅乾:

int limit = Request.Cookies.Count; //Get the number of cookies and 
               //use that as the limit. 
      HttpCookie aCookie; //Instantiate a cookie placeholder 
      string cookieName; 

     //Loop through the cookies 
     for (int i = 0; i < limit; i++) 
     { 
      cookieName = Request.Cookies[i].Name; //get the name of the current cookie 
      aCookie = new HttpCookie(cookieName); //create a new cookie with the same 
                // name as the one you're deleting 
      aCookie.Value = ""; //set a blank value to the cookie 
      aCookie.Expires = DateTime.Now.AddDays(-1); //Setting the expiration date 
                  //in the past deletes the cookie 

      Response.Cookies.Add(aCookie); //Set the cookie to delete it. 
     }