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

前端 未结 11 1223
春和景丽
春和景丽 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

    What is the current approach to make a custom AuthorizeAttribute

    Easy: don't create your own AuthorizeAttribute.

    For pure authorization scenarios (like restricting access to specific users only), the recommended approach is to use the new authorization block: https://github.com/aspnet/MusicStore/blob/1c0aeb08bb1ebd846726232226279bbe001782e1/samples/MusicStore/Startup.cs#L84-L92

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure(options =>
            {
                options.AddPolicy("ManageStore", policy => policy.RequireClaim("Action", "ManageStore"));
            });
        }
    }
    
    public class StoreController : Controller
    {
        [Authorize(Policy = "ManageStore"), HttpGet]
        public async Task Manage() { ... }
    }
    

    For authentication, it's best handled at the middleware level.

    What are you trying to achieve exactly?

提交回复
热议问题