Simple way to check for api key in Web API ASP.NET Core

一曲冷凌霜 提交于 2020-04-16 03:27:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!