在Web API ASP.NET Core中检查api密钥的简单方法
在允许某些Web API端点不受攻击之前,我想简单地检查一下Api密钥(在Authorization标头中发送).为了解决这个问题,我们假设ApiKey为12345
.我只想在达到特定操作方法之前检查此Api Key的值.我不知道这是否需要自定义AuthorizeAttribute或操作过滤器.
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.
简单来说,我发出的请求GET的标头为Authorization: apiKey 12345
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();
}
}
}
在此代码示例中,apiKey
是subStrings[1]