2014-04-21 4 views
0

이 문서를 기반으로 인증 로그인을 만듭니다.
http://www.codeproject.com/Articles/2905/Role-based-Security-with-Forms-Authentication
사용자별로 로그인 할 수 있지만 IsInRole 메서드에 문제가 있습니다. 어떤 역할로 로그인해도 Adminlink는 모든 사용자에게 계속 표시됩니다. 나는 위의 기사와 거의 똑같이했다.IsInRole() 메서드가 작동하지 않습니다?

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; 

        // Get the stored user-data, in this case, our roles 
        string userData = ticket.UserData; 
        string[] roles = userData.Split(','); 
        HttpContext.Current.User = new GenericPrincipal(id, roles); 
       } 
      } 
     } 
    } 

의 Web.config

<configuration> 
    <connectionStrings> 
    <add name="databasestring" connectionString="Data Source=USER-PC;Initial Catalog=database;Integrated Security=True" 
     providerName="System.Data.SqlClient" /> 
    </connectionStrings> 
    <system.web> 
    <authentication mode="Forms"> 
    <forms name="MYWEBAPP.ASPXAUTH" 
     loginUrl="login.aspx" 
     protection="All" 
      path="/"/> 
    </authentication> 
    <authorization> 
     <allow users="*"/> 
     </authorization> 
    </system.web> 
    <location path="admin"> 
    <system.web> 
     <authorization> 
     <!-- Order and case are important below --> 
     <allow roles="Admin"/> 
     <deny users="*"/> 
     </authorization> 
    </system.web> 
    </location> 
    <location path="librarian"> 
    <system.web> 
     <authorization> 
     <!-- Order and case are important below --> 
     <allow roles="Librarian"/> 
      <deny users="*"/> 
     </authorization> 
    </system.web> 
    </location> 
</configuration> 

로그인 버튼의 코드의 코드 Global.asax에

의 코드 : WebForm2.aspx

protected void btnLogin_Click(object sender, EventArgs e) 
    { 
      // Initialize FormsAuthentication, for what it's worth 
      FormsAuthentication.Initialize(); 

      // Create our connection and command objects 
      SqlConnection conn = 
      new SqlConnection("Data Source=USER-PC;Initial Catalog=database;Integrated Security=True"); 
      SqlCommand cmd = conn.CreateCommand(); 
      cmd.CommandText = "SELECT UserType FROM users WHERE [email protected] AND [email protected]"; 

      // Fill our parameters 
      cmd.Parameters.Add("@UserID", SqlDbType.NVarChar, 64).Value = UserID.Value; 
      cmd.Parameters.Add("@UserPassword", SqlDbType.NVarChar, 128).Value = UserPassword.Value; // Or "sha1" 

      // Execute the command 
      conn.Open(); 
      SqlDataReader reader = cmd.ExecuteReader(); 
      if (reader.Read()) 
      { 
       // Create a new ticket used for authentication 
       FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        1, // Ticket version 
        UserID.Value, // Username associated with ticket 
        DateTime.Now, // Date/time issued 
        DateTime.Now.AddMinutes(30), // Date/time to expire 
        true, // "true" for a persistent user cookie 
        reader.GetString(0), // User-data, in this case the roles 
        FormsAuthentication.FormsCookiePath);// Path cookie valid for 

       // Encrypt the cookie using the machine key for secure transport 
       string hash = FormsAuthentication.Encrypt(ticket); 
       HttpCookie cookie = new HttpCookie(
        FormsAuthentication.FormsCookieName, // Name of auth cookie 
        hash); // Hashed ticket 

       // Set the cookie's expiration time to the tickets expiration time 
       if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; 

       // Add the cookie to the list for outgoing response 
       Response.Cookies.Add(cookie); 

       // Redirect to requested URL, or homepage if no previous page 
       // requested 
       string returnUrl = Request.QueryString["/WebForm2.aspx"]; 
       if (returnUrl == null) returnUrl = "/WebForm2.aspx"; 

       // Don't call FormsAuthentication.RedirectFromLoginPage since it 
       // could 
       // replace the authentication ticket (cookie) we just added 
       Response.Redirect(returnUrl); 
      } 
      else 
      { 
       // Never tell the user if just the username is password is incorrect. 
       // That just gives them a place to start, once they've found one or 
       // the other is correct! 
       ErrorLabel.Text = "Username/password incorrect. Please try again."; 
       ErrorLabel.Visible = true; 
      } 

      reader.Close(); 
      conn.Close(); 
     } 
} 

코드

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (User.IsInRole("Admin")) 
     { 
      AdminLink.Visible = true; 
     } 
    } 
+2

"거의"문제 일 수 있습니다. 문제가 무엇인지 알아 내려면 몇 가지 코드가 필요합니다. – jensendp

+0

그 이상 코드 – user3527065

답변

0

인증은 일반적으로 쿠키를 사용하며, 그렇다면 완전한 신뢰할 수있는 데이터를 얻으려면 전체 서버 \ 클라이언트 왕복이 필요합니다. 역할 상태를 확인하기 전에 왕복을 수행하는 사용자를 인증하고 있습니까?

또한 어떻게 \ adminlink 가시성 속성을 설정하고 있습니까? LoginView 컨트롤이나이 데이터를 숨기고있는 다른 방법을 사용하고 있습니까? 몇 가지 기본 코드 샘플을 제공하십시오.


응답 편집 : 를 어디서든 거짓이 링크의 가시성을 설정하는 어디 표시되지 않습니다. 해당 논리를 조건문에 추가하고 \ 또는 HTML 마크 업에서 "visible = false"로 설정하고 수정했는지 확인하십시오.

그래도 해결되지 않으면 중단 점을 설정하여 IsInRole이 어떻게 돌아 왔는지 확인하십시오. 당신이 그것을 기대할 때 참 또는 거짓으로 되돌아 오는 것입니까?

+0

위의 코드를 제공했습니다. – user3527065

관련 문제