【问题标题】:How to authorize one method differently than the controller? (MVC)如何授权一种不同于控制器的方法? (MVC)
【发布时间】:2016-04-03 15:05:52
【问题描述】:

在我目前从事的一个项目中,我拥有三个角色:管理员、超级用户和用户。

管理员可以删除用户、删除 cmets 等,但超级用户也必须能够删除 cmets。所以我建立了一个AdminController 并通过管理员授权它。超级用户必须可以访问一种方法,所以我为超级用户授权了它,但这不起作用。

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
    (... here be only admin methods ...)

    [HttpGet]
    [Authorize(Roles = "Super-user")]
    public ActionResult Delete()
    {
        //deletes a comment
        return View();
    }

    (... here be only admin methods ...)
}

我研究了覆盖 Authorize 属性,但我试图找到一个不需要的解决方案,关于如何为超级用户授权一种方法的任何想法?

管理员作为超级用户必须有权访问方法Delete()。

谢谢!

【问题讨论】:

  • 它应该适用于您的代码。
  • 所以用户应该有Admin和Super-user的角色?那应该可以。
  • 您应该在控制器级别授权 [Authorize(Roles = "Admin, Super-user")]
  • @Felix Cen:但是我在控制器中有更多方法,我不希望超级用户访问这些其他方法。

标签: c# asp.net-mvc


【解决方案1】:

我认为正如@Felix Cen 指出的那样,指定这应该在控制器上工作

[Authorize(Roles = "Admin, Super-user")]

然后在方法级别指定这个

[Authorize(Roles = "Super-user")]

或者,您可以使用 this 问题中指出的拒绝属性

public class DenyAttribute : AuthorizeAttribute
{

    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        if (httpContext == null) {
            throw new ArgumentNullException("httpContext");
        }

        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated) {
            return false;
        }

        if (Users.Length > 0 && Users.Split(',').Any( u => string.Compare( u.Trim(), user.Identity.Name, StringComparer.OrdinalIgnoreCase))) {
            return false;
        }

        if (Roles.Length > 0 && Roles.Split(',').Any( u => user.IsInRole(u.Trim()))) {
            return false;
        }

        return true;
    }

这里还有一个问题(我觉得我有点像this这里的具体答案)

我个人对此的看法是拆分控制器。只需创建 另一个控制器用于您不需要身份验证的操作。

或者你可以:

BaseController
doesn't require authentication - here you have all your "base stuff" :).

BaseAuthController : BaseController
all actions here require authentication.

这样您就可以在需要时进行身份验证,只需派生 来自特定的班级。

【讨论】:

    猜你喜欢
    • 2018-01-18
    • 2016-11-02
    • 1970-01-01
    • 2018-03-01
    • 2013-08-03
    • 1970-01-01
    • 2021-07-26
    • 2019-12-15
    • 2015-12-03
    相关资源
    最近更新 更多