1

I'm running an application on .net core 2.1. I added a wsdl web service through connected services that generated me a WcfServiceClient successfully.

When using Basic Autorization it works fine.

here is the class I use for calling a helloword soap method :

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;
}

This is working fine with servers that are running on Basic Authorization. I am using the same credentials with SOAP UI and it is working very well. and I dont even need to specify the enter image description here

<==> Now The Problem <=>

I have a second server that runs with NTLM Authorization. I done it all :'( but nothing seems working.

1 - I changed my service.clientCredential.Username to service.clientCredential.Windows and I added service.clientCredential.Windows.domain

2 - I changed the Header also from "Basic " + Convert... to "Ntlm " + Convert...

3 - I added the domain in the header and I put it first and last position.

when I use SOAP UI, it is working just fine. enter image description here

I dont know what to do else Please Help.

Wajdi Chamakhi
  • 426
  • 5
  • 16

2 Answers2

5

I finally found it out.

So here My new Code to get the service with NTLM Authorization

    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;
    }

and then you call your WebService normaly

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

now For Basic Authorization :

    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;
    }

and then you call your WebService normaly

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

Happy coding every one

Wajdi Chamakhi
  • 426
  • 5
  • 16
  • Getting this error in both method The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via at System.ServiceModel.Channels.TransportChannelFactory`1.ValidateScheme(Uri via) at System.ServiceModel.Channels.HttpChannelFactory`1.ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via) at System.ServiceModel.Channels.HttpChannelFactory`1.OnCreateChannelCore(EndpointAddress remoteAddress, Uri via) at System.ServiceModel.Channels.ChannelFactoryBase`1.InternalCreateChannel(EndpointAddress address, Uri via) ... .... .... – Raju Paladiya Nov 28 '19 at 06:48
0

For Windows Authentication, the .net core application passing the running identity, eg, it run passing the Application identity when you hosting in IIS.

Here are two options for you:

  1. Configure the .net core app run under the domain account user.
  2. If you prefer configuring the username and password in code, you could try 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();
        }
    
    }
    
Edward
  • 28,296
  • 11
  • 76
  • 121