0

I'm trying to implement the Authorize attribute in my WebApi Controllers. I've found resources on how to implement Authorize, and even that I need to set the Thread and HttpContext Principals when implementing Authorization. But I can't find an example of how/where I write the Authorization logic.

public class MyController : ApiController
{
    [Route("")]
    [Authorize]
    public async Task<IHttpActionResult> Get() {}
}
public class MyAuthorizationProvider
{
    public void AuthorizeIGuess()
    {
        string authHeader = HttpContext.Request.Headers.GetValues("Authorization").FirstOrDefault();

        // do stuff with auth header
        // create principal

        HttpContext.Current.User = ...;
        Thread.CurrentPrincipal = ...;
    }
}

How do I setup MyAuthorizationProvider so that it is used for Authorize, and is this how I set my auth context?

Muhammed Shevil KP
  • 1,406
  • 1
  • 14
  • 21
micah
  • 6,213
  • 6
  • 35
  • 62

1 Answers1

1

You need to inherit AuthorizeAttribute like

public class MyAuthorizationProvider : AuthorizeAttribute  
{
  //Write your validation logic here. 
}

and use this override authorization attribute like

    public class MyController : ApiController
  {
    [Route("")]
    [MyAuthorizationProvider]
    public async Task<IHttpActionResult> Get() {}
  }

When you inherit AuthorizeAttribute, it will gives you some override method to implement your logic in better way, use that also. For more details check this answer.

Community
  • 1
  • 1
MANISH KUMAR CHOUDHARY
  • 3,144
  • 2
  • 20
  • 30
  • In examples where simply `[Authorize]` is used are those just abstract examples? Is it possible to reuse the `[Authorize]` attribute or is it always extended/renamed? – micah Feb 01 '17 at 03:28