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); */ }
,相关文章
- 利用查询条件对象,在Asp.net Web API中实现对业务数据的分页查询处理
- Redis总结(五)缓存雪崩和缓存穿透等问题 Web API系列(三)统一异常处理 C#总结(一)AutoResetEvent的使用介绍(用AutoResetEvent实现同步) C#总结(二)事件Event 介绍总结 C#总结(三)DataGridView增加全选列 Web API系列(二)接口安全和参数校验 RabbitMQ学习系列(六): RabbitMQ 高可用集群
- ASP.NET Web API 2 使用 DelegatingHandler(委托处理程序)实现签名认证
- 利用过滤器Filter和特性Attribute实现对Web API返回结果的封装和统一异常处理
- 利用DelegatingHandler实现Web Api 的Api key校验