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); */ }
,相关文章
- Laravel 5 中使用 JWT(Json Web Token) 实现基于API的用户认证
- 如何利用新浪官方的短网址API接口实现T.cn短链接的压缩生成
- Web API应用架构在Winform混合框架中的应用(4)--利用代码生成工具快速开发整套应用...
- ASP.NET Web Api 实现数据的分页(转载)
- ASP.NET Web Api 实现数据的分页
- 利用高德地图官方提供的API实现模拟定位的功能
- 小程序API(1.15)利用API函数实现扫码、打电话和 添加联系人的方法 - Luna彬
- 微信小程序的Web API接口设计及常见接口实现
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【四】——实现模型工厂,依赖注入以及格式配置
- 在Web API 2 中实现带JSON的Patch请求