Over the last posts I showed how you can associate HTTP request fields with authentication logic. The last missing piece is the MessageHandler for Web API (see here for more info on message handlers).
A very simple implementation would look like this:
public class SimpleAuthenticationHandler : DelegatingHandler
_authN = new HttpAuthentication(configuration);
protected override Task<HttpResponseMessage> SendAsync(
Thread.CurrentPrincipal = _authN.Authenticate(request);
return base.SendAsync(request, cancellationToken);
On every incoming request the handler passes the request message to the authentication engine. The engine runs that by the configuration and returns a principal which gets set on Thread.CurrentPrincipal.
The real implementation also needs to deal with exceptions, claims transformation and setting an appropriate Authenticate header on the response if authorization fails.
At application start time, you would wire up the handler and the corresponding configuration from global.asax:
public static void ConfigureGlobal(HttpConfiguration globalConfig)
public static AuthenticationConfiguration CreateConfiguration()
var config = new AuthenticationConfiguration();
config.DefaultAuthenticationScheme = “Basic”;
config.AddBasicAuthentication((userName, password) =>
userName == password);
Disclaimer: All the code is based on ASP.NET Web API RC and .NET 4.5 RC. I currently don’t have the time to maintain both .NET 4.0/WIF and .NET 4.5 versions.
Will you have time to post a running (simple) example of this?
Would be great! Thank you :-)
I get a System.ArrayTypeMismatchException when trying to add the AuthenticationHandler to the globalConfig.MessageHandlers. Any idea what could cause this problem, I can’t seem to figure it out. Thanks!
Heard that before, but no idea. Maybe a version mismatch?
Thought of that too, gonna try to set it up from scratch againg and see what happens. I’ll let you know. Thanks for the great work btw!
If any finds this page due to @bouwmanmark’s issue with System.ArrayTypeMismatchException, the default Web API template maybe using System.Net.Http v18.104.22.168 as the reference to use rather than v22.214.171.124.
I had to replace the reference in my Web API project and remove the assembly binding from my web.config.
In the samples. Should I use WebApiSecurity or ClaimsBasedAuthorization for Web Api Integration using JWT? I’m assuming WebApiSecurity and that the clients there are representations of consuming the api and providing the authorization.
We will have third party api developers authenticating to use our API.
great. Thank You. BTW, awesome job on IdentityServer and Model. Once I have a full understanding of the project, I would love to start helping out.