在 Web API ASP.NET Core 中检查 api 密钥的简单方法

Bri*_*man 1 authorization authorize-attribute asp.net-core asp.net-core-webapi asp.net-core-2.1

在允许某些 Web API 端点受到攻击之前,我想简单地检查在授权标头中发送的 Api 密钥。为了这个问题,我们假设 ApiKey 是12345. 我只想在到达特定操作方法之前检查此 Api Key 的值。我不知道这是否需要自定义 AuthorizeAttribute 或操作过滤器。

Kha*_*yen 5

简单地说,我用标头发出一个请求 GET 是 Authorization: apiKey 12345

授权属性实现如下所示:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此代码示例中,apiKeysubStrings[1]