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.

5
  • 2
    Are you actually authenticated? Authorization won't kick into policies until you have an identity. Commented Mar 1, 2016 at 20:56
  • I'm not. Looks like I'm looking for Basic Authentication middleware.. Commented Mar 1, 2016 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? Commented Mar 1, 2016 at 22:36
  • I would like to add token to every request(into header) and validate it by custom logic. Commented Mar 1, 2016 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. Commented Mar 1, 2016 at 22:52

1 Answer 1

6

I believe you are missing this part:

services.AddSingleton<IAuthorizationHandler, MyRequirementHandler>();

Source

Sign up to request clarification or add additional context in comments.

3 Comments

Is possible to apply a Policy without a name so that the Policy will be applied in all authorize request ?
How to get access to headers from here?
@mr_squall if you need access to headers in order to get the user/claims principal you can use context.user.Identity by typecasting it as ClaimsIdentity

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.