利用DelegatingHandler实现Web Api 的Api key校验

Posted 名字什么都是浮云

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用DelegatingHandler实现Web Api 的Api key校验相关的知识,希望对你有一定的参考价值。

client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-ApiKey","00000");

编写ApiKeyHandler

public class ApiKeyHandler : DelegatingHandler
    {
        public string Key { get; set; }

        public ApiKeyHandler(string key,HttpConfiguration httpConfiguration)
        {
            this.Key = key;
            InnerHandler = new HttpControllerDispatcher(httpConfiguration); 
        }

        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (!ValidateKey(request))
            {
                var response = new HttpResponseMessage(HttpStatusCode.Forbidden);
                var tsc = new TaskCompletionSource<HttpResponseMessage>();
                tsc.SetResult(response);
                return tsc.Task;
            }
            return base.SendAsync(request, cancellationToken);
        }

        private bool ValidateKey(HttpRequestMessage message)
        {
            IEnumerable<string> apiKeyHeaderValues = null;

            if (message.Headers.TryGetValues("X-ApiKey", out apiKeyHeaderValues))
            {
                var apiKeyHeaderValue = apiKeyHeaderValues.First();
                  return (apiKeyHeaderValue == this.Key)
                // ... your authentication logic here ...
                /*
               var username = (apiKeyHeaderValue == "00000" ? "Maarten" : "OtherUser");

               var usernameClaim = new Claim(ClaimTypes.Name, username);
                var identity = new ClaimsIdentity(new[] { usernameClaim }, "ApiKey");
                var principal = new ClaimsPrincipal(identity);

                Thread.CurrentPrincipal = principal;
             */
            }

            /*
            var query = message.RequestUri.ParseQueryString();
            string key = query["key"];
            return (key == this.Key);
            */
        }

配置到特定的路由上去

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: null,
                handler: new ApiKeyHandler("12345", GlobalConfiguration.Configuration)
                
            );

 

以上是关于利用DelegatingHandler实现Web Api 的Api key校验的主要内容,如果未能解决你的问题,请参考以下文章

在 ASP.NET Core Web API 中注册一个新的 DelegatingHandler

在 ASP.NET Core 5.0 Web API 中实现 DelegatingHandler?

WebApi 中响应的 DelegatingHandler

将 DelegatingHandler 与 HttpClient 上的自定义数据一起使用

预检 CORS 请求未调用 WebApi DelegatingHandler

如果 ExceptionHandler 捕获到异常,则不会调用 DelegatingHandler