8

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.

Chatumbabub
  • 1,557
  • 2
  • 18
  • 30
  • 2
    Are you actually authenticated? Authorization won't kick into policies until you have an identity. – blowdart Mar 01 '16 at 20:56
  • I'm not. Looks like I'm looking for Basic Authentication middleware.. – Chatumbabub Mar 01 '16 at 22:18
  • Do you mean basic as in HTTP auth, or basic as in, I want to shove this identity on every request whilst I test? – blowdart Mar 01 '16 at 22:36
  • I would like to add token to every request(into header) and validate it by custom logic. – Chatumbabub Mar 01 '16 at 22:51
  • If a JWT token will suffice there is middleware for that. If you want your own token, then you need to write your own middleware to create an identity before any policies ever get evaluated. – blowdart Mar 01 '16 at 22:52

1 Answers1

6

I believe you are missing this part:

services.AddSingleton<IAuthorizationHandler, MyRequirementHandler>();

Source

regnauld
  • 4,046
  • 3
  • 23
  • 22