Just thought I would throw up a quick post on how to implement an delegatinghandler in WCF webapi preview 5+. Preview 5 introduced some breaking changes to most of the samples out on the net I could find. After some digging around here is how to implement a simple API key check using the delegating handler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | public interface IKeyVerifier { bool Verify(string key); } public class KeyVerifier : IKeyVerifier { public bool Verify(string key) { return true; //TODO implement your own check logic here } } public class ApiKeyVerificationChannel : DelegatingHandler { public const string KeyHeaderName = "X-AuthKey"; IKeyVerifier keyVerifier; public ApiKeyVerificationChannel(HttpMessageHandler innerChannel) : this(innerChannel, new KeyVerifier()) { } public ApiKeyVerificationChannel() { keyVerifier = new KeyVerifier(); } public ApiKeyVerificationChannel(HttpMessageHandler innerChannel, IKeyVerifier keyVerifier) : base(innerChannel) { this.keyVerifier = keyVerifier; } protected override TaskSendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { IEnumerable values = null; if (request.Headers.TryGetValues(KeyHeaderName, out values)) { var key = values.First(); if (this.keyVerifier.Verify(key)) { return base.SendAsync(request, cancellationToken); } } return Task.Factory.StartNew(() => { var response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.Content = new StringContent("Your Api key is invalid."); return response; }); } } |
Be sure to include the reference to the handler in global.asax. This is also slightly updated from samples around the net
1 | var config = new HttpConfiguration() { EnableTestClient = true, MessageHandlers = {typeof(ApiKeyVerificationChannel)} }; |
