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?

1 Answer 1

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.

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

1 Comment

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?

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.