• 利用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

  • 相关阅读:
    2020牛客暑期多校(三)
    贪心算法
    高级搜索题集
    状态压缩dp
    [kuangbin带你飞]专题二 搜索进阶
    [kuangbin带你飞]专题一 简单搜索
    HDU 1695 GCD(求两区间的互质数对+容斥原理)
    UVA 10200 Prime Time(简单素数判定预处理)
    HDU 1452 FZU 1053 Happy 2004(逆元函数+因子和函数+大指数取模化简公式)
    低三位的数是8的倍数就可以被8整除
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/12409713.html
Copyright © 2020-2023  润新知