Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom Authorization in ASP.NET Core (ASP.NET 5)

I would like to have custom implementation of [Authorize] attribute in controlles.

This is what I did.

  1. StartupClass in ConfigureServices

    services.AddAuthorization(options =>
    {    
        options.AddPolicy("Authorize", policy =>
        {   
             policy.AddRequirements(new MyRequirement());
        });
    });
    
  2. MyRequirement

    public class MyRequirement : AuthorizationHandler<MyRequirement>, IAuthorizationRequirement
    {
        protected override void Handle(AuthorizationContext context, MyRequirement requirement)
        {
            //some work
            //if shloud be authorized
            context.Succeed(requirement);
        }
    }
    
  3. TestController

    [Authorize("Authorize")]
    [Route("api/[controller]")]
    public class TestController : Controller
    {
      ...
    }
    

What I'm I missing? MyRequirement authorizationhader is never called. Thank you.

like image 610
Chatumbabub Avatar asked Mar 01 '16 20:03

Chatumbabub


1 Answers

I believe you are missing this part:

services.AddSingleton<IAuthorizationHandler, MyRequirementHandler>();

Source

like image 74
regnauld Avatar answered Oct 20 '22 01:10

regnauld