繁体   English   中英

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

[英]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");
    }
}

通过下面给出的链接

[ http://www.asp.net/web-forms/tutorials/security]

您需要了解的有关表单身份验证的所有内容都在此asp.net安全教程系列中涵盖了。 这是非常基础且循序渐进的,因此希望您在遵循它时可能没有任何问题。

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

听起来就好像.NET成员资格和角色提供者所走的方向是错误的。 .NET框架将代替您对用户进行身份验证,然后告诉Microsoft的成员资格和角色库谁已登录以及他们具有什么权限,而是使用成员资格提供程序对用户进行身份验证,并且该框架还将告诉您的应用程序用户具有哪些权限。通过使用角色提供程序。 本质上,您将为成员资格和角色提供程序构建插件。

这里关于实施会员供应商,和更多的信息在这里对实现角色提供类似的信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM