2011-04-25 131 views
1

我继承了一个不完全正常工作的ASP.NET C#应用程序。我被告知使用表单身份验证来防止未经授权的用户访问特定的子目录。ASP.NET C# - 使用表单身份验证设置基于角色的安全性

我有一个理解表单身份验证的问题。这是一个公共互联网网站,所有用户都可以访问该网站的主要部分。但是,有一个仅限于某些用户的子目录。我知道用户是有效的,因为他们将输入用户名和密码,我会在数据库中查找它们。我已经将这些行添加到子目录的web.config文件中。

<configuration> 
    <appSettings/> 
    <connectionStrings/> 
    <system.web> 
     <authorization> 
     <allow roles="Administrators, Examiners"/> 
      <deny users="*"/> 
     </authorization> 
    </system.web> 

问题是如何在我的代码中设置用户属于某个角色。

这里是伪代码。

如果用户名和密码匹配,那么

设置该用户角色考官。

我不知道我需要将用户设置为角色的代码。

回答

1

看看你的会员资格数据库。

要在这里开始,你去与登录方法:

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; 
} 

你可以在认证方法中检查用户凭据:依赖于特定的角色

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"); 
    } 
} 
+0

链接给出这是有帮助的。我发现我的前辈已经创建了我需要的表格。网络配置也设置了,但没有代码。我能够改变web.config指向我的本地数据库。然后,你给我的电话Membership.ValidateUser工作时,我给它一个示例用户和密码。我遇到的问题是我的用户密码是加密的,所以我无法知道那里有什么。所以我需要代码来创建一个用户并给他一个密码或修改一个现有用户的密码,这样我就可以得到一个成功的电话。 – 2011-04-27 20:31:58

+0

我弄清楚我需要什么。尽管其他答案也很有帮助,但我将其标记为最好的。 – 2011-04-28 13:17:26

+0

@鲍勃,我很高兴这有帮助。验证密码是在服务器端完成的,您无需担心这一点。您可以点击Up-Vote按钮来获得所有有帮助的答案,而不用接受他们的答案给每个人一些信用。 – 2011-04-28 15:33:56

0

这个asp.net security tutorial series涵盖了您需要了解的有关表格认证的一切。这是非常基本的,一步一步的,所以希望你不会有任何问题在跟踪它。

0

您将需要实现与数据库配合使用的成员资格和角色提供程序。成员资格提供程序将对用户进行身份验证并跟踪哪个用户已登录。角色提供程序将确定用户具有的权限。

听起来好像你正在从错误的方向接近问题,就.NET成员和角色提供者而言。您不是通过验证用户身份,然后告诉Microsoft的登录成员和角色库以及他们拥有什么权限,.NET框架将使用成员资格提供程序对用户进行身份验证,并且该框架还会告诉您的应用程序用户有什么权限通过使用角色提供者。您将基本上为会员和角色提供商构建插件。

请参阅here关于实施成员资格提供者的更多信息,关于实施角色提供者的相似信息请参阅here

相关问题