MVC 覆盖 AllowAnonymous 属性

MVC override AllowAnonymous attribute

有没有办法覆盖 AllowAnonymous 属性?我已经实现了从数据库加载用户菜单和按钮的自定义授权,如下所示:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new MyCustomAuthorization()); // Custom Authorization for Rights & Priveleges
}

上面的工作正常。

现在我想在用户通过身份验证后允许访问某些操作,在这种情况下无需检查授权。示例:

[Authorize]
public class MenusAndButtonsController : BaseController
{
    [Authenticated] // my custom attribute that will check if user is logged in or not
    public JsonResult GetGeneralMenuAndButtons()
    {
        using (MealPlannerAuthorizationEntities repository = new MealPlannerAuthorizationEntities())
        {
            var MenusAndButtons = repository.MP_AUTH_Menus.Where(x => x.IsButton == false && x.IsListButton == false).Select(c => new { DisplayText = c.MenuName, Value = c.MenuId }).OrderBy(x => x.DisplayText).ToList();
            return Json(new { Result = "OK", Options = MenusAndButtons }, JsonRequestBehavior.AllowGet);
        }
    }
}

而不是 AllowAnonymous,我尝试创建自己的自定义属性 [Authenticated] 来检查用户是否登录。如果用户已登录,它将 return true 并且 GetGeneralMenuAndButtons 将继续其操作。

Actually AllowAnonymous class is simple empty sealed attribute class.

所以当我们用AllowAnonymous属性装饰一个action方法时,AuthorizeAttributeonAuthorization方法简单地忽略授权和认证检查。所以在我的例子中,我还必须创建一个属性(一个空白密封 class 继承自属性 class)并稍微修改 OnAuthorization 方法。

下面是完整的实现:

public sealed class AuthenticateAttribute : Attribute
{
    public AuthenticateAttribute() { }
}

然后覆盖 Authorize 属性的 onAuthorization 方法(当然我假设您已经实现了自定义授权过滤器)。

public override void OnAuthorization(AuthorizationContext filterContext)
{
    bool IsAuthenticAttribute =
        (filterContext.ActionDescriptor.IsDefined(typeof(AuthenticateAttribute), true) ||
        filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AuthenticateAttribute), true)) &&
        filterContext.HttpContext.User.Identity.IsAuthenticated;

    if (!IsAuthenticAttribute)
    {
        base.OnAuthorization(filterContext);
    }
}

最后用我们新的 Authenticate 属性修饰您的操作方法:

[Authenticate]
public JsonResult GetParentMenus()
{
    using (MealPlannerAuthorizationEntities repository = new MealPlannerAuthorizationEntities())
    {
        var parentMenus = repository.MP_AUTH_Menus.Where(x => x.IsButton == false && x.IsListButton == false).Select(c => new { DisplayText = c.MenuName, Value = c.MenuId }).OrderBy(x => x.DisplayText).ToList();
        return Json(new { Result = "OK", Options = parentMenus }, JsonRequestBehavior.AllowGet);
    }
}