利用DelegatingHandler实现Web Api 的Api key校验
2016-03-31 16:50
375 查看
客户端在请求Web Api时可以有以下两种方式提供API key
基于Querystring提供Api key基于Request header体统API key
client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("X-ApiKey","00000");
编写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) );
相关文章推荐
- 同步与异步的区别
- linux下安装phpstudy
- 纯原创
- 声明与输入的类型不同会怎样
- android app(1)—apk的组成
- 免安装PL/SQL无法连接本地ORACLE数据库解决方法
- 《15个数字的排序代码》15电气1班43号
- 中断中处理延时及一些函数的调用规则(中断调i2c驱动有感)--中断中的延迟delay与printk函数的冲突【转】
- 微信支付学习记录1
- Java包装类
- IOS TextField伴随键盘移动
- Python excel转xml
- 解决svn一直报Error validating server certificate for https://XXXX fingerprint
- Android 应用利用反射机制获取/设置系统属性值
- Android Intent传值反馈,向后传递,要求返回的传值
- codeforces_652D. Nested Segments(树状数组、二分)
- activity的启动方式 requestCode和resultCode的区别
- Push Notification(三)
- SecureCRT 常用命令
- Cordova官方插件 -- Icon + SplashScreen