简体   繁体   English

MVC3 中的角色管理

[英]Role Management in MVC3

I want to add a functionality to application such that only admin can create users and he can provide access to particular pages to user.我想向应用程序添加一个功能,这样只有管理员才能创建用户,并且他可以向用户提供对特定页面的访问权限。

He can create roles and can provide users different roles.他可以创建角色并且可以为用户提供不同的角色。

I am using Visual Studio 2010 and building this application in MVC3.我正在使用 Visual Studio 2010 并在 MVC3 中构建此应用程序。

Please give me suggestions to make over it.请给我建议以弥补它。

Thanks in advance.提前致谢。

1.Decorate your user creation and permission setting actions with Authorize attribute (Notify, that usage of Roles property of AuthorizeAttribute requires implementation of MembershipProvider (standart or custom) and registering it in web.config) 1.使用 Authorize 属性装饰您的用户创建和权限设置操作(通知,使用 AuthorizeAttribute 的 Roles 属性需要实现 MembershipProvider(标准或自定义)并在 web.config 中注册)

public class AccountController : Controller
{
[HttpGet, Authorize(Roles = "Admin")]
public ViewResult CreateUser()
{
    return View();
}

[HttpPost, Authorize(Roles = "Admin")]
public ActionResult CreateUser()
{
    //... call service method to create user
}

[HttpPost, Authorize(Roles = "Admin")]
public ActionResult AssignPageToUser(int userId, string controllerName, string ActionName)
{
    //... insert record into table (UserPermissions) with attributes (userId, actionName, controllerName)
    }
// other methods without decoration by authorize attribute
}

Next paragraphs are correct if you really want to have full control on action permissions separately for each user.如果您真的想分别完全控制每个用户的操作权限,那么接下来的段落是正确的。 If you think, that your permissions can group in finite and small number on roles - you can decorate all actions/controllers by authorize attribute and specify roles, for which action/controller available: [Authorize("Customer, Manager, RegionalAdmin")] and give admin possibility to assign roles to users.如果您认为,您的权限可以在角色上进行有限和少量分组 - 您可以通过授权属性装饰所有操作/控制器并指定角色,哪些操作/控制器可用: [Authorize("Customer, Manager, RegionalAdmin")]并让管理员可以为用户分配角色。 But remember, that in is enough to be in only 1 of listed roles to get access, you can't require by this attribute, for example and Admin, and Manager roles.但请记住,仅在列出的角色中的 1 个角色中就足以获得访问权限,您不能通过此属性要求,例如管理员和经理角色。 If you want to require necessarily more than 1 role, use multiple attributes:如果您想需要超过 1 个角色,请使用多个属性:

public class MyController:Controller
{
[Authorize(Roles = "Manager")]
[Authorize(Roles = "Admin")]
public ActionResult Action1()
{
//...
}
}

2.For your pages you can create your own filter attribute, inherited from authorize attribute, that will check, if action is available for user (i think you want to assign actions but not views to user). 2.对于您的页面,您可以创建自己的过滤器属性,从授权属性继承,这将检查用户是否可以使用操作(我认为您想要分配操作而不是视图给用户)。

public UserPermissionRequiredAttribute: AuthorizeAttribute
{
public OnAuthorization(AuthorizationContext filterContext)
{
var isAuthenticated = filterContext.HttpContext.User.Identity.IsAuthenticated;
var userName = filterContext.HttpContext.User.Identity.Name;
var actionName = filterContext.ActionDescriptior.ActionName;
var controllerName = filterContext.ActionDescriptior.ControllerDescriptor.ControllerName;
    if (isAuthenticated && myUserActionPermissionsService.UserCanAccessAction(userName, actionName, contollerName)
{
filterContext.Result = HttpUnauthorizedResult(); // aborts action executing
}
}
}

3.Decorate actions (controllers), that accessible for users granted by admin: 3.装饰操作(控制器),管理员授予的用户可以访问:

MySpecialController: Controller
{
[UserPermissionRequired]
Action1()
{
//...
}

[UserPermissionRequired]
Action2()
{
//...
}

Action3()
{
//...
}

} }

I don't recommend to use base controller for that aim, because attribute usage is more flexible (you have control on action/controller level instead of only controller level), it is better way to implement separated responsibility.我不建议为此目的使用基础 controller,因为属性使用更灵活(您可以控制动作/控制器级别,而不仅仅是 controller 级别),这是实现责任分离的更好方法。 Base controller and filter attribute usage correlated as polymorphism and switch operator.基本 controller 和过滤器属性使用与多态性和切换运算符相关。

You're asking a very broad question, and it would take some time to review all your requirements.您提出了一个非常广泛的问题,并且需要一些时间来审查您的所有要求。 In any case, you could start by adding a user property to a controller from which all other controllers inherit.在任何情况下,您都可以首先将用户属性添加到所有其他控制器继承的 controller。 Then, you could interrogate that user instance to determine whether they have access to the current route.然后,您可以询问该用户实例以确定他们是否有权访问当前路由。 This solution should give you the foundation you need to add some administrative views for your business requirements.该解决方案应该为您提供为您的业务需求添加一些管理视图所需的基础。

public class MegaController
{
    protected User CurrentUser { get; set; }

    protected override void Initialize(RequestContext context)
    {
        if (requestContext.HttpContext.User.Identity.IsAuthenticated)
        {
            var userRepository = new UserRepository();
            CurrentUser = userRepository.GetUser(
                requestContext.HttpContext.User.Identity.Name);
        }
    }
}

The User and UserRepository types can be your own design. UserUserRepository类型可以是您自己的设计。 You could use LINQ To Entities to wrap a table named "User" and then within your controllers, you could have access to any fields in that table.您可以使用 LINQ To Entities 来包装一个名为“用户”的表,然后在您的控制器中,您可以访问该表中的任何字段。

Then, subclass all controllers from MegaController然后,从MegaController子类化所有控制器

public class AdminController : MegaController
{
    public ActionResult Action1()
    {
        return View();
    }
}

public class SomeOtherController : MegaController
{
    public ActionResult Action1()
    {
        return View();
    }
}

Now, this doesn't completely solve your "admin" issue.现在,这并不能完全解决您的“管理员”问题。 To do so, you could include logic in MegaController.Initialize() to interrogate the request information.为此,您可以在MegaController.Initialize()中包含逻辑以询问请求信息。 Once you have the requested route and user in context, your code could make a decision whether to allow the request, redirect it, etc.一旦您在上下文中获得了请求的路由和用户,您的代码就可以决定是否允许请求、重定向请求等。

protected override void Initialize(RequestContext context)
{
    // ...
    if(context.HttpContext != null)
    {
        if(context.HttpContext.Request.Path == "some/restricted/route" 
            && CurrentUser.Role != "Admin")
        {
            // or similar error page
            var url = Url.Action("UnAuthorized", "Error");
            context.HttpContext.Response.Redirect(url);
        }
    }
}

One caveat with this method is that any new controllers added to your application would have to inherit from MegaController , an architecture that could be easily missed by future developers on the project.这种方法的一个警告是,添加到应用程序中的任何新控制器都必须继承自MegaController ,项目的未来开发人员很容易错过这种架构。

Read about plain old forms authentication to add support for roles and user management.阅读普通的旧forms 身份验证以添加对角色和用户管理的支持。

Then use the [Authorize(Roles="RoleName1")] on controllers or actions to control access.然后在控制器或操作上使用[Authorize(Roles="RoleName1")]来控制访问。

Check MvcMembership , also available on Nuget .检查MvcMembership ,也可用于Nuget You will have all the basics for User Management in an ASP.NET MVC 3 site.您将在 ASP.NET MVC 3 站点中掌握用户管理的所有基础知识。

You will need a user / role provider.您将需要一个用户/角色提供者。 Read this tutorial to learn how to setup a database that will hold your users and roles.阅读本教程以了解如何设置将保存您的用户和角色的数据库。 Once it is setup, you will have all the stored procedures needed for first setup / manual testing created.设置完成后,您将创建首次设置/手动测试所需的所有存储过程。

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

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