ASP.NET Web API Self-Host with Windows Authentication

前端 未结 9 1301
不知归路
不知归路 2021-01-30 11:31

I am trying to use the ASP.NET Web API Self-Host option with Windows authentication so I can determine the logged on user and ultimately accept or reject the user based on their

9条回答
  •  無奈伤痛
    2021-01-30 12:09

    Similar to tpeczek's answer but updated to reflect HTTPS usage. tpeczek's answer doesn't work for HTTPS because the call to base.OnConfigureBinding(httpBinding); with HTTPS overwrites the changes. Additionally, you cannot use httpBinding.Security.Mode = HttpBindingSecurityMode.TransportCredentialOnly; with HTTPS.

    Use a custom HttpSelfHostConfiguration:

    public class NtlmSelfHostConfiguration : HttpSelfHostConfiguration
    {
        public NtlmSelfHostConfiguration(string baseAddress)
            : base(baseAddress)
        { }
    
        public NtlmSelfHostConfiguration(Uri baseAddress)
            : base(baseAddress)
        { }
    
        protected override BindingParameterCollection OnConfigureBinding(
            HttpBinding httpBinding)
        {
            if (this.BaseAddress.Scheme == Uri.UriSchemeHttps)
            {
                var ret = base.OnConfigureBinding(httpBinding);
                httpBinding.Security.Transport.ClientCredentialType =
                    HttpClientCredentialType.Ntlm;
                return ret;
            }
    
            httpBinding.Security.Mode = HttpBindingSecurityMode.TransportCredentialOnly;
            httpBinding.Security.Transport.ClientCredentialType = 
                HttpClientCredentialType.Ntlm;
            return base.OnConfigureBinding(httpBinding);
        }
    }
    

    Then, you can do

    var config = new NtlmSelfHostConfiguration("http://myComputerName:8080");
    

    or

    var config = new NtlmSelfHostConfiguration("https://myComputerName:8443");
    

    to get a configuration to pass into new HttpSelfHostServer(config)

提交回复
热议问题