Is there a way to override AllowAnonymous attribute? I have implemented custom authorization that loads user menus & buttons from database as below:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyCustomAuthorization()); // Custom Authorization for Rights & Priveleges
}
The above works fine.
Now I want to allow access to some action if a user is authenticated, no need to check authorization in this case. Example:
[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);
}
}
}
Instead of AllowAnonymous, I am trying to create my own custom attribute [Authenticated] that will check if the user is logged in or not. If user is logged in it will return true and the GetGeneralMenuAndButtons will continue its operation.
So when we decorate an action method with
AllowAnonymousattribute, theonAuthorizationmethod ofAuthorizeAttributesimply ignores authorization and authentication checking. So in my case I also had to create an attribute (a blank sealed class inheriting from attribute class) and modify theOnAuthorizationmethod little bit.Below is the complete implementation:
Then override the
onAuthorizationmethod of Authorize attribute (of course I am assuming you already have custom authorization filter implemented).Finally decorate your action method with our new Authenticate attribute: