问题
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.
回答1:
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]
来源:https://stackoverflow.com/questions/53586736/simple-way-to-check-for-api-key-in-web-api-asp-net-core