.net 核心 2 及更高版本:使用 NTLM 授权如何连接服务 WcfServiceClient SOAP?

.net core 2 and Higher : connected services WcfServiceClient SOAP with NTLM Authorization how to?

我是 运行 .net core 2.1 上的应用程序。 我通过成功生成 WcfServiceClient 的连接服务添加了 wsdl Web 服务。

当使用 基本授权 时它有效很好

这是我用来调用 helloword soap 方法的class:

public string HellowWorld(string input)
{
    string wsRes = null;
    try
    {
        var service = new WorkerProcessServiceClient();
        var url = $"http://ServerUrl/Directory/WsName.svc";
        UriBuilder uriBuilder = new UriBuilder(url);

        service.Endpoint.Address = new EndpointAddress(uriBuilder.Uri);
        service.ClientCredentials.UserName.UserName = Username;
        service.ClientCredentials.UserName.Password = Password;

        using (OperationContextScope scope = new OperationContextScope(service.InnerChannel))
        {
            HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
            httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] =
                "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(service.ClientCredentials.UserName.UserName
                + ":"
                + service.ClientCredentials.UserName.Password));
            OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
            wsRes = service.HelloWorldAsync(input, RetailContext).GetAwaiter().GetResult();
            service.Close();
        }
    }
    catch (Exception ex)
    {
        wsRes = ex.Message;
    }
    return wsRes;
}

这在 运行 基本授权 的服务器上工作正常。我在 SOAP UI 中使用相同的凭据,并且运行良好。我什至不需要指定

<==>现在是问题<=>

我有第二台服务器运行 NTLM 授权。 我都做了 :'( 但似乎没有任何效果。

1 - 我将 service.clientCredential.Username 更改为 service.clientCredential.Windows 并添加了 service.clientCredential.Windows.domain

2 - 我也将 Header 从 "Basic " + Convert... 更改为 "Ntlm " + Convert...

3 - 我在 header 中添加了域,并将其放在第一个和最后一个位置。

当我使用 SOAP UI 时,它工作得很好。

我不知道还能做什么请帮忙。

对于Windows 身份验证,.net 核心应用程序传递运行ning 身份,例如,当您托管在IIS 中时,它运行 传递应用程序身份。

这里有两个选项供您选择:

  1. 在域帐户用户下配置.net 核心应用运行。
  2. 如果您更喜欢在代码中配置用户名和密码,您可以尝试WindowsIdentity.RunImpersonated

    public class HomeController : Controller
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
                int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);
        const int LOGON32_PROVIDER_DEFAULT = 0;
        //This parameter causes LogonUser to create a primary token.   
        const int LOGON32_LOGON_INTERACTIVE = 2;
        public IActionResult About()
        {
            SafeAccessTokenHandle safeAccessTokenHandle;
            bool returnValue = LogonUser("username", "domain", "password",
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                out safeAccessTokenHandle);
            WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () =>
            {
                NTLMWebServiceSoapClient client = new NTLMWebServiceSoapClient(NTLMWebServiceSoapClient.EndpointConfiguration.NTLMWebServiceSoap);
                var result = client.HelloWorldAsync().Result;
                ViewData["Message"] = result.Body.HelloWorldResult;
            });
    
            return View();
        }
    
    }
    

终于找到了

所以这里是我的新代码,用于通过 NTLM 授权获得服务

    private WcfServiceClient MyNtlmConfiguredService()
    {
        BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
        basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
        //this is for enabling Ntlm if you wanna work with basic you just 
        // you just replace HttpClientCredentialType.Ntlm by HttpClientCredentialType.Basic
        basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;

        EndpointAddress endpoint = new EndpointAddress("http://ServerUrl/Directory/WsName.svc");

        var client = new WcfServiceClient(basicHttpBinding, endpoint);

        NetworkCredential myCreds = new NetworkCredential("Username", "pas**rd", "Domain");

        client.ClientCredentials.Windows.ClientCredential = myCreds;
        client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

        return client;
    }

然后您正常调用 WebService

MyNtlmConfiguredService().HellowWorld(input).getAwaiter().getResult();

现在对于基本授权:

    private CustomerWcfServiceClient MyBasicConfiguredService()
    {
        var service = new CustomerWcfServiceClient();
        CustomerWcfServiceClient client = null;
        string wsRes = null;

        BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
        basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;//mandatory
        basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;//mandatory

        EndpointAddress endpoint = new EndpointAddress("http://ServerUrl/Directory/WsName.svc");

        client = new CustomerWcfServiceClient(basicHttpBinding, endpoint);


        client.ClientCredentials.UserName.UserName = "UserName";
        client.ClientCredentials.UserName.Password = "Pa**word";

        return client;
    }

然后您正常调用 WebService

MyBasicConfiguredService().HellowWorld(input).getAwaiter().getResult();

祝大家编码愉快