How do you create a custom AuthorizeAttribute in ASP.NET Core?

前端 未结 11 1205
春和景丽
春和景丽 2020-11-21 17:19

I\'m trying to make a custom authorization attribute in ASP.NET Core. In previous versions it was possible to override bool AuthorizeCore(HttpContextBase httpContext)

11条回答
  •  甜味超标
    2020-11-21 18:11

    Based on Derek Greer GREAT answer, i did it with enums.

    Here is an example of my code:

    public enum PermissionItem
    {
        User,
        Product,
        Contact,
        Review,
        Client
    }
    
    public enum PermissionAction
    {
        Read,
        Create,
    }
    
    
    public class AuthorizeAttribute : TypeFilterAttribute
    {
        public AuthorizeAttribute(PermissionItem item, PermissionAction action)
        : base(typeof(AuthorizeActionFilter))
        {
            Arguments = new object[] { item, action };
        }
    }
    
    public class AuthorizeActionFilter : IAuthorizationFilter
    {
        private readonly PermissionItem _item;
        private readonly PermissionAction _action;
        public AuthorizeActionFilter(PermissionItem item, PermissionAction action)
        {
            _item = item;
            _action = action;
        }
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            bool isAuthorized = MumboJumboFunction(context.HttpContext.User, _item, _action); // :)
    
            if (!isAuthorized)
            {
                context.Result = new ForbidResult();
            }
        }
    }
    
    public class UserController : BaseController
    {
        private readonly DbContext _context;
    
        public UserController( DbContext context) :
            base()
        {
            _logger = logger;
        }
    
        [Authorize(PermissionItem.User, PermissionAction.Read)]
        public async Task Index()
        {
            return View(await _context.User.ToListAsync());
        }
    }
    

提交回复
热议问题