zoukankan      html  css  js  c++  java
  • 利用DelegatingHandler实现Web Api 的Api key校验

    客户端在请求Web Api时可以有以下两种方式提供API key

    • 基于Querystring提供Api key

    http://localhost:57967/Api/Values?key=12345

    • 基于Request header体统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)
                    
                );
    
  • 相关阅读:
    JDK的命令详解
    聊天室java socket
    怎么实现利用Java搜索引擎收集网址的程序
    Hibernate实现对多个表进行关联查询
    如何学好J2ME?
    谈谈Java工程师应该具有的知识
    【经营智慧】005.眼光盯着未来
    【成功智慧】002.对任何小事都不要掉以轻心
    【经营智慧】008.要想赚钱,就得打破既有的成见
    【思维智慧】004.砸碎障碍的石头,把它当做钥匙
  • 原文地址:https://www.cnblogs.com/ywolf123/p/5340938.html
Copyright © 2011-2022 走看看