2

I'd like to simply check for an Api Key — sent up in the Authorization header — prior to allowing certain Web API endpoints from getting hit. For the sake of this question, let's assume the ApiKey is 12345. I just want to check the value of this Api Key prior to reaching the specific action method. I can't figure out whether or not this calls for a custom AuthorizeAttribute or an action filter.

Khai Nguyen
  • 935
  • 5
  • 17
Brian David Berman
  • 7,514
  • 26
  • 77
  • 144

1 Answers1

7

Simply, I make a request GET with header is Authorization: apiKey 12345

The authorization attribute implementation look like below:

public class AuthorizationFilterAttribute : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var apiKey = context.HttpContext.Request.Headers["Authorization"];

        if (apiKey.Any())
        {
            // this would be your business
            var subStrings = apiKey.ToString().Split(" ");
            if (!(subStrings.Length >= 2 && subStrings[0] == "apiKey" && subStrings[1].Any()))
            {
                context.Result = new NotFoundResult();
            }
        }
        else
        {
            context.Result = new NotFoundResult();
        }
    }
}

In this code sample, apiKey is subStrings[1]

Khai Nguyen
  • 935
  • 5
  • 17