Can you enable [Authorize] for controller but disable it for a single action?

前端 未结 4 1082
长发绾君心
长发绾君心 2021-01-31 20:04

I would like to use [Authorize] for every action in my admin controller except the Login action.

[Authorize (Roles = \"Administrator\"         


        
4条回答
  •  难免孤独
    2021-01-31 20:46

    May be it's not actual, but I wrote my custom attribute:

    public class SelectableAuthorizeAttribute : AuthorizeAttribute
    {
        public SelectableAuthorizeAttribute(params Type[] typesToExclude)
        {
            _typesToExlude = typesToExclude;
        }
    
        private readonly Type[] _typesToExlude;
    
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            bool skipAuthorization = _typesToExlude.Any(type => filterContext.ActionDescriptor.ControllerDescriptor.ControllerType == type);
    
            if (!skipAuthorization)
            {
                base.OnAuthorization(filterContext);
            }
        }
    }
    

    And then registered it in my global filetrs:

    filters.Add(new SelectableAuthorizeAttribute(typeof(MyController)));
    

    Hope that it will be useful for someone

提交回复
热议问题