繁体   English   中英

如何在mvc.net中实现安全认证和角色机制?

[英]How to implement security authentication and roles mechanism in mvc.net?

我正在尝试在我的第一个mvc应用程序中实现角色机制,所以我可以在actionResults上面使用数据注释([Authorize(Roles =“Administrator”)])。

我读了很多关于securtiy身份验证,成员身份和角色的内容,但仍无法解决所有这些问题。 例如,我在这里阅读:

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文件在<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)
    {
..
    }

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

下面介绍如何覆盖它并将membership和roleManagement类替换为可以对用户进行身份验证并使用您自己的第三方库为其授予角色的简单类。

您需要实现以下两个类,以提高可读性,将它们放在解决方案的同一文件夹中:

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");

        }

这就是全部,希望它有所帮助。

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

祝好运。

暂无
暂无

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

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