c# - 一个 Action 可以授权给定用户/角色以外的所有人吗?

标签 c# asp.net-mvc

使用 [Authorize] 属性可以轻松地将操作设置为仅由特定用户或角色允许。例如。

[Authorize(Roles = "Administrator")]
public ActionResult Index()
{
  ...

但是,当我想要反转时,我遇到了一个问题。有没有一种方法可以使用 MVC 框架功能允许所有经过身份验证的用户按名称或角色指定的用户除外?

所需的用法类似于:

[DoNotAuthorize(Roles = "RestrictedUser")]
public ActionResult Index()
{
  ...

最佳答案

一个相当简单的解决方案是派生自 AuthorizeAttribute 类并覆盖其 AuthorizeCore 方法,交换其真/假逻辑。

/// <summary>
/// Authorizes any authenticated user *except* those who match the provided Users or Roles.
/// </summary>
public class DoNotAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// This is effectively a copy of the MVC source for AuthorizeCore with true/false logic swapped.
    /// </summary>
    /// <param name="httpContext">The HTTP context, which encapsulates all HTTP-specific information about an individual HTTP request.</param>
    /// <returns>true if the user is authorized; otherwise, false.</returns>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }
        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated)
        {
            return false;
        }

        string[] usersSplit = SplitString(Users);
        if ((usersSplit.Length > 0) && usersSplit.Contains<string>(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
        {
            return false;
        }

        string[] rolesSplit = SplitString(Roles);
        if ((rolesSplit.Length > 0) && rolesSplit.Any<string>(new Func<string, bool>(user.IsInRole)))
        {
            return false;
        }

        return true;
    }

    /// <summary>
    /// This is a direct copy of the MVC source for the internal SplitString method.
    /// </summary>
    /// <param name="original">The original string to split.</param>
    /// <returns>An array of strings.</returns>
    internal static string[] SplitString(string original)
    {
        if (string.IsNullOrWhiteSpace(original))
        {
            return new string[0];
        }
        return (from piece in original.Split(new[] { ',' })
                let trimmed = piece.Trim()
                where !string.IsNullOrEmpty(trimmed)
                select trimmed).ToArray<string>();
    }
}

关于c# - 一个 Action 可以授权给定用户/角色以外的所有人吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13870833/

相关文章:

javascript - asp.net mvc如何从jquery控件中保存数据

javascript - 在查询字符串处传递 '+'

asp.net-mvc - 将 Web 表单 ASP.NET 应用程序迁移到 MVC

c# - 任务线程中抛出的异常,未被 UnobservedTaskException 捕获

c# - Entity Framework 获取包括一些值的属性

c# - User.IsInRole 始终使用 token 身份验证返回 false

JQuery Ajax 调用给出 404 'Resource Not Found' 错误,但正常的 URL 调用没问题

c# - 锁语句的内存屏障

c# - 在不知道名称的情况下获取第一列的值

asp.net-mvc - Mvc4 捆绑、缩小和 AngularJS 服务