How to support multiple authentication in self host
Since we build web api self host story on top of WCF HttpTransportBindingElement, the multiple authentication is not support on WCF for 4.0. Here is the exception you will get if you tried to set the authentication scheme on httptransport binding element.
"System.ArgumentException: The 'Negotiate, Anonymous' authentication scheme has been specified on the HTTP factory. However, the factory only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous."
The good news is that this has been fixed in .NET framework 4.5 Beta. This is the link https://msdn.microsoft.com/en-us/library/ms171868(v=vs.110).aspx#windows_communication_foundation.
"Ability to support multiple authentication modes on a single WCF endpoint when using the HTTP transport and transport security. "
So with that fix in mind, web api now provides an extensibility point for people to set the authentication schemes.
Step 1: Derive from HttpSelfHostConfiguration, and register an action to modify TransportBindingElement, and modify the authentication scheme in the action.
Code Snippet
- class MultipleAuthenticationHttpConfiguration : HttpSelfHostConfiguration
- {
- public MultipleAuthenticationHttpConfiguration(string baseAddress)
- : base(baseAddress)
- {
- }
- protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
- {
- httpBinding.ConfigureTransportBindingElement = new Action<HttpTransportBindingElement>(ConfigureTransportBindingElement);
- return base.OnConfigureBinding(httpBinding);
- }
- void ConfigureTransportBindingElement(HttpTransportBindingElement bindingElement)
- {
- // uncomment the following line if running on 4.5
- // bindingElement.AuthenticationScheme = AuthenticationSchemes.Negotiate | AuthenticationSchemes.Anonymous;
- bindingElement.AuthenticationScheme = AuthenticationSchemes.Negotiate;
- }
- }
Step 2: use the derived the configuration object instead
Code Snippet
- var config = new MultipleAuthenticationHttpConfiguration(Program.BaseAddress);
- config.Routes.MapHttpRoute("Default", "{controller}", new { controller = "Sample" });
- SetupConfig(config);
- server = new HttpSelfHostServer(config);
- server.OpenAsync().Wait();
- Console.WriteLine("Service listening at: " + Program.BaseAddress);