【问题标题】:How to implement security authentication and roles mechanism in mvc.net?mvc.net中如何实现安全认证和角色机制?
【发布时间】:2015-03-25 10:02:10
【问题描述】:

我正在尝试在我的第一个 mvc 应用程序中实现角色机制,因此我可以使用 actionResults 上方的数据注释 ([Authorize(Roles="Administrator")])..

我阅读了很多关于安全身份验证、成员资格和角色的信息,但仍然无法解决所有这些问题。例如,我在这里读到:

http://stackoverflow.com/questions/10742709/asp-net-mvc4-security-authentication-and-authorization

甚至尝试复制以下内容: http://www.codeproject.com/Articles/654846/Security-In-ASP-NET-MVC

我实现了 roleProvider 和 AccountMembershipProvider 接口,但我必须在这里遗漏一些重要的东西,因为它不起作用..

我需要一个很好的教程,说明我需要实现什么以及如何将所有内容结合起来。

你能解释一下如何实现吗?

【问题讨论】:

  • 你没有提到任何关于 web.config 的内容。当有人尝试登录应用程序时,您需要告诉您的应用程序使用 AccountMembershipProvider 和 RoleProvider。你试过吗?
  • 你能详细说明一下吗?

标签: asp.net-mvc security asp.net-roles


【解决方案1】:

我不久前建立了这个教程.. 它结合了来自几个来源的一些现有教程。所以,也许你已经看过其中的一部分了。

为了让它工作,您必须在您的应用程序中实现以下所有代码。

让我们开始吧:

当您的应用程序 web.config 文件在<system.web> 标记下具有以下部分时,将激活数据注释机制:

  <system.web>

    <!-- authentication section activates the auth system -->

    <authentication mode="Forms">
       <forms loginUrl="~/yourLoginControllerName/YourLoginActionResult" timeout="2880" />
    </authentication>

    <!-- membership section defines which class is used to check authentication, in this example, this is the default class -->

    <membership defaultProvider="AccountMembershipProvider">
      <providers>
        <clear/>
        <add name="AccountMembershipProvider"
             type="yourProjectName.Web.Infrastructure.AccountMembershipProvider" />
      </providers>
    </membership>

    <!-- roleManager section defines which class is used to check roles for users, in this example, the default class is used -->

    <roleManager enabled="true" defaultProvider="AccountRoleProvider">
      <providers>
        <clear/>
        <add name="AccountRoleProvider"
             type="yourProjectName.Web.Infrastructure.AccountRoleProvider" />
      </providers>
    </roleManager>
..
  </system.web>

装饰允许您控制哪些角色可以访问哪些控制器操作,并定义控制器操作是需要身份验证才能访问它们还是可以被所有用户访问。控制是通过控制器中的以下属性来完成的,例如:

public class HomeController : Controller
{
    [Authorize]
    public ActionResult Index()
    {
..
    }

    [Authorize(Roles = "Administrator, KingOnRails")]
    public ActionResult Edit(int Id)
    {
..
    }

默认系统限制您按原样使用数据注释。它需要数据库连接来创建用户表和角色。

下面将向您展示如何覆盖它并将成员资格和角色管理类替换为简单的类,这些类可以使用您自己的 3rd 方库对用户进行身份验证并赋予他们角色。

您需要实现以下 2 个类,为了更好的可读性,请将它们放在解决方案中的同一文件夹中:

public class AccountMembershipProvider : MembershipProvider
{
        public override bool ValidateUser(string username, string password)
        {
            if (username == "KingOnRails")
                return true;
            return false;
        }
}

还有:

public class AccountRoleProvider : RoleProvider
{

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
                //Here you can implement insertion of <key, value> = <user, role> to a global dictionary maintained in Global.asax file... 
        }

        public override string[] GetRolesForUser(string username)
        {
            if (username == "Roy Doron")
                return new string[1] { "User" };
            else if (username == "KingOnRails")
                return new string[1] { "Administrator" };
            return null;
        }

        public override bool RoleExists(string roleName)
        {
            if ((roleName == "Administrator") || (roleName == "User"))
                return true;
            else
                return false;
        }
}

就是这样.. 现在您只需在登录控制器中编写自己的流程(如果有),如果没有,则需要实现一个登录页面。

当用户尝试登录到您的系统时,登录控制器应调用成员资格 ValidateUser() 方法,如果成功,则需要为该用户创建 Web 表单身份验证票,然后将用户重定向到您想要的任何位置,例如:

[HttpPost]
public ActionResult Login()
        {
            string user = Request.Params["user"];
    // calls the AccountMembershipProvider.ValidateUser()
            if (Membership.ValidateUser(user, Request.Params["password"]))
            {
                FormsAuthentication.SetAuthCookie(user, true);
                return Redirect("/Home/WhereEver");
            }
            else
                return Redirect("/Home/Login");

        }

就是这样,希望对你有帮助。

如果您有任何其他问题,请随时提出。

祝你好运。

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 2018-11-12
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 2017-10-03
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多