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

    ASP.NET Web API服务端框架由一组HttpMessageHandler经过“首尾相连”而成,管道式设计使该框架具有很高的扩展性。虽然ASP.NET Web API服务端框架的作用是“处理请求、响应回复”,但是具体采用的处理策略因具体的场景而不同。我们不可能也没有必要创建一个“万能”的处理器来满足所有的请求处理场景,所以倒不如让某个处理器只负责某个单一的消息处理功能。针对具体的应用场景中,我们可以根据具体的消息处理需求来选择所需的处理器并共同组成一个完成的消息处理管道。在这里这个用于完成某个单一消息处理功能的处理器就是HttpMessageHandler。

    HttpMessageHandler是抽象类,DelegatingHandler是它的派生类

    编写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)
                    
                );

     

     

    参考:

    https://blog.csdn.net/dyllove98/article/details/9707507

    https://www.cnblogs.com/ywolf123/p/5340938.html

  • 相关阅读:
    中共中央办公厅的机构设置(局、室)
    清理winsxs文件夹(系统更新文件)的第三方工具
    通用的MIME类型:application/octet-stream
    “IIS7.5无法写入配置文件web.config”的解决方案
    刷新组策略的命令
    windows网络和共享中心“查看基本网络信息并设置连接”为“未知”的解决方案
    使 windows 无需输入开机密码自动进入系统
    windows server 2008 R2 的 FTP 防火墙的正确配置方法
    搜狗浏览器不能使用拖拽搜索的解决方案
    无法启动 Diagnostic Policy Service(服务错误 1079)的解决方案
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/12409713.html
Copyright © 2011-2022 走看看