MVC覆盖AllowAnonymous属性

suo*_*dev 4 authentication custom-attributes filterattribute asp.net-mvc-4

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

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

以上工作正常.

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

[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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

而不是AllowAnonymous,我试图创建我自己的自定义属性[Authenticated],将检查用户是否登录.如果用户登录,它将返回true并GetGeneralMenuAndButtons继续其操作.

suo*_*dev 6

实际上AllowAnonymous类是简单的空密封属性类.

因此,当我们使用AllowAnonymous属性修饰动作方法时,该onAuthorization方法AuthorizeAttribute只是忽略授权和身份验证检查.所以在我的情况下,我还必须创建一个属性(从属性类继承的空白密封类)并OnAuthorization稍微修改该方法.

以下是完整的实施:

public sealed class AuthenticateAttribute : Attribute
{
    public AuthenticateAttribute() { }
}
Run Code Online (Sandbox Code Playgroud)

然后覆盖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);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后使用我们新的Authenticate属性装饰你的action方法:

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)