利用DelegatingHandler实现Web Api 的Api key校验
生活随笔
收集整理的這篇文章主要介紹了
利用DelegatingHandler实现Web Api 的Api key校验
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
客戶端在請求Web Api時可以有以下兩種方式提供API key
-
基于Querystring提供Api key
http://localhost:57967/Api/Values?key=12345
-
基于Request header體統API key
編寫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校验的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 刘静(说一说刘静的简介)
- 下一篇: IIS线程池与ASP.NET线程池