ASP MVC Authorize all actions except a few

前端 未结 7 637
逝去的感伤
逝去的感伤 2020-12-13 00:29

I have a controller and I would like to require Authorization for all actions by default except a couple. So in the example below all actions should require authentication e

7条回答
  •  清歌不尽
    2020-12-13 01:25

    Ok, this is what I did. If there is a better way let me know.

    public class NotAuthorizeAttribute : FilterAttribute
    {
        // Does nothing, just used for decoration
    }
    
    public class BaseController : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Check if this action has NotAuthorizeAttribute
            object[] attributes = filterContext.ActionDescriptor.GetCustomAttributes(true);
            if (attributes.Any(a => a is NotAuthorizeAttribute)) return;
    
            // Must login
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }
    

提交回复
热议问题