【问题标题】:MVC Condintional AuthorizationMVC 条件授权
【发布时间】:2013-01-30 18:29:47
【问题描述】:

我正在尝试找出控制对我的应用程序不同部分的访问的正确方法。

我的应用有 3 个部分。

  1. 管理员
  2. 超级用户
  3. 普通用户

我已经阅读了http://blogs.msdn.com/b/rickandy/archive/2011/05/02/securing-your-asp-net-mvc-3-application.aspx,所以我明白即使我有一个区域,我也不想将它用于我的授权。

我的想法是有 3 个基本控制器类,每个部分一个。类似于AdminBaseControllerSuperUserBaseControllerRegularUserBaseController

我知道我可以为每个角色添加一个AuthorizeAttribute,但我想在我的设置中存储所需的角色,所以我无法在属性中设置这些角色。

所以我想我需要继承 AuthorizeAttribute 并覆盖 OnAuthorization,这就是我卡住的地方。这是我目前所拥有的。

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.ControllerContext.Controller is AdminBaseController)
        {
            //do something
        }
        else if (actionContext.ControllerContext.Controller is SuperUserBaseController)
        {
            //do something
        }
        else if (actionContext.ControllerContext.Controller is RegularUserBaseController)
        {
            //do something
        }
        else
        {
            //someone forgot to use a base controller
            //deny be default
        }
    }

我想我只是将RolesUsers 属性设置为正确的值,然后在最后调用base.OnAuthorization。这似乎是一个合理的解决方案?另外,要拒绝所有,我应该将两个属性都设置为""吗?

如果我离题了,请指点我一个更好的方向。

【问题讨论】:

  • 看起来很完美。这是整个 Q 吗?

标签: c# asp.net-mvc asp.net-mvc-4 authorization


【解决方案1】:

看看 Fluent Security http://www.fluentsecurity.net/

我喜欢它比 .NET 中内置的安全功能要好得多。他们的示例中有基于角色的权限示例。它也比你想要做的更干净。

这是一个关于如何使用 Fluent Security 为您的站点配置安全性的示例

/// <summary>
/// Configuration Helper for Fluent Security. See http://www.fluentsecurity.net
/// </summary>
public static class SecurityConfig
{
    public static void Configure()
    {
        SecurityConfigurator.Configure(c =>
        {
            c.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated);
            c.GetRolesFrom(() => (HttpContext.Current.Session["Roles"] as string[]));

            // Blanket Deny All
            c.ForAllControllers().DenyAnonymousAccess();                

            // Publicly Available Controllers
            c.For<HomeController>().Ignore();
            c.For<RegistrationsController>().Ignore();
            c.For<LoginController>().Ignore();

            // Only allow Admin To Create
            c.For<ReservationsController>(x => x.Create())
             .RequireRole(UserRoles.Admin.ToString());

            c.For<ReservationsController>(x => x.Edit(""))
             .RequireRole(UserRoles.Admin.ToString(),UserRoles.User.ToString());

            c.For<ReservationsController>(x => x.Delete(""))
             .RequireRole(UserRoles.Admin.ToString(),UserRoles.User.ToString());           
        });
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 2015-04-10
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多