[英]SQL Database Powered C# & ASP.Net Role based authentication control
[英]ASP.NET C# - Setting up Role Based Security with Forms Authentication
我继承了一个不能完全正常工作的ASP.NET C#应用程序。 我被告知要使用表单身份验证来防止未经授权的用户访问某些子目录。
我在理解表单身份验证时遇到问题。 这是一个公共互联网站点,所有用户都可以访问该站点的主要部分。 但是,有一个子目录仅限于某些用户。 我知道用户是有效的,因为他们将输入用户名和密码,并在数据库中查找它们。 我已将这些行添加到子目录的web.config文件中。
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<authorization>
<allow roles="Administrators, Examiners"/>
<deny users="*"/>
</authorization>
</system.web>
问题是如何在代码中设置用户属于某个角色。
这是伪代码。
如果用户名和密码匹配,则
将此用户角色设置为“检查者”。
我不知道将用户设置为角色所需的代码。
查看您的会员数据库。
要从这里开始,请使用login方法:
protected void LoginButton_Click(object sender, EventArgs e)
{
// Validate the user against the Membership framework user store
if (Membership.ValidateUser(UserName.Text, Password.Text))
{
// Log the user into the site
FormsAuthentication.RedirectFromLoginPage(UserName.Text, RememberMe.Checked);
}
// If we reach here, the user's credentials were invalid
InvalidCredentialsMessage.Visible = true;
}
您可以在authenticate方法中检查用户凭据:
protected void myLogin_Authenticate(object sender, AuthenticateEventArgs e)
{
// Get the email address entered
TextBox EmailTextBox = myLogin.FindControl("Email") as TextBox;
string email = EmailTextBox.Text.Trim();
// Verify that the username/password pair is valid
if (Membership.ValidateUser(myLogin.UserName, myLogin.Password))
{
// Username/password are valid, check email
MembershipUser usrInfo = Membership.GetUser(myLogin.UserName);
if (usrInfo != null && string.Compare(usrInfo.Email, email, true) == 0)
{
// Email matches, the credentials are valid
e.Authenticated = true;
}
else
{
// Email address is invalid...
e.Authenticated = false;
}
}
else
{
// Username/password are not valid...
e.Authenticated = false;
}
}
对于根据特定角色的重定向,请使用以下代码:
protected void Login1_LoggedIn(object sender, EventArgs e)
{
if (Roles.IsUserInRole(Login1.UserName, "Admin"))
{
Response.Redirect("~/Admin/Default.aspx");
}
else if (Roles.IsUserInRole(Login1.UserName, "Examiner"))
{
Response.Redirect("~/Examiner/Default.aspx");
}
else
{
Response.Redirect("~/Login.aspx");
}
}
通过下面给出的链接
您需要了解的有关表单身份验证的所有内容都在此asp.net安全教程系列中涵盖了。 这是非常基础且循序渐进的,因此希望您在遵循它时可能没有任何问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.