이 문서를 기반으로 인증 로그인을 만듭니다.
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;
}
}
"거의"문제 일 수 있습니다. 문제가 무엇인지 알아 내려면 몇 가지 코드가 필요합니다. – jensendp
그 이상 코드 – user3527065