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.
Asked
Active
Viewed 6,747 times
2

Khai Nguyen
- 935
- 5
- 17

Brian David Berman
- 7,514
- 26
- 77
- 144
1 Answers
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
-
How does this get called/used? Attribute decorator? Wired up in the config? – Brian David Berman Dec 04 '18 at 01:09
-
This is an attribute and we call by `[TypeFilter(typeof(AuthorizationFilterAttribute))]` or `[AuthorizationFilterAttribute]` on action – Khai Nguyen Dec 04 '18 at 01:23