ASP.NET C# - 使用表单身份验证设置基于角色的安全性

时间:2011-04-25 15:36:38

标签: c# asp.net forms-authentication

我继承了一个不完全正常工作的ASP.NET C#应用程序。我被告知使用表单身份验证来防止未经授权的用户访问某些子目录。

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

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

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

这是伪代码。

如果用户名和密码匹配,则

将此用户角色设置为审查员。

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

4 个答案:

答案 0 :(得分: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");
    }
}

答案 1 :(得分:0)

asp.net security tutorial series中介绍了您需要了解的有关表单身份验证的所有信息。这是非常基础和一步一步的,所以希望你可能没有任何问题跟随它。

答案 2 :(得分:0)

您需要实现适用于您的数据库的成员资格和角色提供程序。成员资格提供程序将对用户进行身份验证并跟踪登录的用户。角色提供程序将确定用户拥有的权限。

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

有关实施成员资格提供程序的详细信息,请参阅here;有关实施角色提供程序的类似信息,请参阅here

答案 3 :(得分:0)

相关问题