I've written a Windows Application to test a connection to a clients SAP web services. The web service call requires X509 certificate security.
After reading various articles on the internet I've come up with three ways to attach the X509 certificate to the web service call. Unfortunately all of these attempts return a '401 Unauthorised Access'. However, I can connect to the web service via the URL in IE.
Does anybody have any sugestions as to what I may be doing wrong? I am using WSE 3.0 and the three methods I am using to attach the certificate are as follows:-
Certificate
X509Certificate2 oCert = GetSecurityCertificate(oCertificate);
svc.ClientCertificates.Add(oCert);
Token
X509SecurityToken oToken = GetSecurityToken(oCertificate);
svc.RequestSoapContext.Security.Tokens.Add(oToken);
Policy
SAPX509Assertion sapX509Assertion = new SAPX509Assertion(oCertificate, oStoreLocation, oStoreName, oFindType);
svc.SetPolicy(sapX509Assertion.Policy());
GetSecurityToken() and GetSecuirtyCertificate both search the certificate store. The SAPX509Assertion does this:-
public SAPX509Assertion(String certSubject, StoreLocation oStoreLocation, StoreName oStoreName, X509FindType oFindType)
{
ClientX509TokenProvider = new X509TokenProvider(oStoreLocation,
oStoreName, certSubject, oFindType);
ServiceX509TokenProvider = new X509TokenProvider(oStoreLocation,
oStoreName, certSubject, oFindType);
Protection.Request.EncryptBody = false;
Protection.Response.EncryptBody = false;
}
Update
OK, I have a WCF call now in place. I couldn't use the BasicHttpBinding method shown by Eugarps as it complained that I was connecting to a https address and expected http...which made sense. The code I now have is:-
var binding = new WSHttpBinding();
binding.MaxReceivedMessageSize = int.MaxValue;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
binding.Security.Mode = SecurityMode.Transport;
WCFConnection.CreateAbsenceWSlow.ZWSDHTM_GB_AMS_CREATEABS_lowClient client;
CreateAbsenceWSlow.ZfhhrGbbapiZgeeamsCreateabsResponse response;
CreateAbsenceWSlow.ZfhhrGbbapiZgeeamsCreateabs data;
//Assign address
var address = new EndpointAddress(sUrl);
//Create service client
client = new CreateAbsenceWSlow.ZWSDHTM_GB_AMS_CREATEABS_lowClient(binding, address);
//Assign credentials
client.ClientCredentials.UserName.UserName = sUserName;
client.ClientCredentials.UserName.Password = sPassword;
response = new CreateAbsenceWSlow.ZfhhrGbbapiZgeeamsCreateabsResponse();
data = new WCFConnection.CreateAbsenceWSlow.ZfhhrGbbapiZgeeamsCreateabs();
response = client.ZfhhrGbbapiZgeeamsCreateabs(data);
It's still failing to connect to the SAP web service. The error I am receiving is "The HTTP request is unauthorized with client authentication scheme 'Negotiate'". I've also tried using
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
which returned a similar error.
Does anybody have any further suggestions or ideas of where I am going wrong?
Now, this is all coming from my own experience so some of it may be wrong, but here's how I understand the process (I received no documentation and my company had no experience in calling SAP before I began doing it).
SAP WS calls are only supported by WCF BasicHttpBinding, and as far as I can tell, only using plain-text credentials. This means you will want to use IPSec or HTTPS if you need to make your communication private (outside intranet, or sensitive data within intranet). Our SAP server does not have HTTPS configured, but we use VPN with IPSec for external communication. Important to note is that, by default, SAP GUI also does not make communication private. In this situation, you are being no less secure by using the method detailed below than the business user down the hall who is looking up sensitive data in GUI 7.1. Here's how I connect to our SAP server internally:
//Create binding
//Note, this is not secure but it's not up to us to decide. This should only ever be run within
//the VPN or Intranet where IPSec is active. If SAP is ever directly from outside the network,
//credentials and messages will not be private.
var binding = new BasicHttpBinding();
binding.MaxReceivedMessageSize = int.MaxValue;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
//Assign address
var address = new EndpointAddress(Host);
//Create service client
var client = new SAP_RFC_READ_TABLE.RFC_READ_TABLEPortTypeClient(binding, address);
//Assign credentials
client.ClientCredentials.UserName.UserName = User;
client.ClientCredentials.UserName.Password = Password;
As far as I have been able to determine, message-level security is not supported, and bindings other than basicHttpBinding (SOAP 1.1) are not supported.
As I said, this is all from experience and not from training, so if anybody can add something through comments, please do so.
I've faced the same problem and it seems I've found the sollution here: http://ddkonline.blogspot.com/2009/08/calling-sap-pi-web-service-using-wcf.html.
CustomBinding binding = new CustomBinding();
binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));
HttpsTransportBindingElement transport = new HttpsTransportBindingElement();
transport.AuthenticationScheme = AuthenticationSchemes.Basic;
//transport.ProxyAuthenticationScheme = AuthenticationSchemes.Basic;
transport.Realm = "XISOAPApps";
binding.Elements.Add(transport);
var address = new EndpointAddress("https://foooo");
........ create client proxy class
service.ClientCredentials.UserName.UserName = "<login>";
service.ClientCredentials.UserName.Password = "<password>";
Unfortunatelly I'm not able to use WCF in my application, I have to stick with .NET 2.0 and WSE 3.0, and I wounder if anybody was able to find sollution to that?
After all this time, the client has finally obtained someone to deal with the issue from their SAP end of things. Turns out the WSDL files we were supplied were incorrect and the certification had been done wrong. I reran my code with the new WSDL files and it worked first time.
Does your certificate happen to be mapped to a valid user in your user store?
Related
I'm having difficulties trying to connect to a 3rd-party SOAP server that requires two-way SSL. On the client side I have our certificate and private key, and I also have the self-signed certificate chain provided by the service provider. What I'm essentially trying to do is the C# equivalent of this Python code:
r = requests.post(
url,
verify=(ca_path),
cert=(client_public_path, client_private_path),
headers=headers,
data=body)
Back in C# land, I've subscribed to the service and made it as far as this:
var endpoint = new EndpointAddress("https://server.endpoint.com/");
var binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
using (var service = new MyServiceReference.ServerClient(binding, endpoint))
{
X509Certificate certificate = LoadCertificate(client_public_path, client_private_path);
service.ClientCredentials.ClientCertificate.Certificate = certificate;
// how to set server CA Bundle?
var response = service.SomeMethod(new Request{...});
At a bit of a loss though trying to figure out how to set the server-side chain? I have the two certs that are in the chain file, and I can also separate them out and load them into a X509Certificate2Collection if need be, just can't seem to figure out what to do with it after that?
The only other thing I've tried is assigning a custom validator on the server certificate:
service.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom;
service.ClientCredentials.ServiceCertificate.Authentication.CustomCertificateValidator = new MyValidator();
The custom validator's Validate method never gets called thoough, which if I'm not mistaken would suggest it's a either a problem with the client cert or the binding config?
We are writing a client to a WCF service that uses both a CSR certificate and basic authentication.
Our C# client is generated via Visual Studio and we can programmatically set the certificate and the username/password. However, we have to manually send the Basic Auth header otherwise we receive the error:
'The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Basic realm="HttpBasicAuthentication"'.'
Our code is:
var myBinding = new WSHttpBinding();
myBinding.Security.Mode = SecurityMode.Transport;
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
myBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
var ea = new EndpointAddress("https://example.org/myservice");
var client = new MandateWebServiceClient(myBinding, ea);
client.ClientCredentials.UserName.UserName = "wally";
client.ClientCredentials.UserName.Password = "walliesWorld";
client.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2("C:\\some\\path\\to\\csr.pfx", "password");
using (var scope = new OperationContextScope(client.InnerChannel))
{
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[HttpRequestHeader.Authorization] =
"Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(client.ClientCredentials.UserName.UserName + ":" + client.ClientCredentials.UserName.Password));
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
client.create();
}
With the above code, we can successfully talk to the service. If we remove the lines in the using block, the authentication scheme changes to Anonymous, and we get the error above.
The above arrangement seems a little hackey. We have tried all the SecurityMode settings possible and SecurityMode.Transport with HttpClientCredentialType.Certificate is the only combination that allows the certificate to be accepted. Setting or not setting MessageCredentialType.UserName appears to have no effect on the system.
Is there any .Net Framework way of providing both the certificate and the basic authentication header rather than manually adding the header?
How does the server use both Certificate authentication and Basic authentication? This seems superfluous. Because it is secure to authenticate the client with a certificate (issue the certificate and establish the relationship between the server and client), why do we need to authenticate the client with Basic Authentication? Thereby, are you sure that the client needs to provide a certificate? In my opinion, the server may have used Transport Security mode, and set up a Basic authentication, so the client may need not to provide a certificate.
Here is the server side configuration I thought.
Server.
Uri uri = new Uri("https://localhost:9900");
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
Client (invocation by adding service reference, the client proxy class/binding type is auto-generated via the service MEX endpoint, https://localhost:9900/mex)
ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
client.ClientCredentials.UserName.UserName = "administrator";
client.ClientCredentials.UserName.Password = "abcd1234!";
Based on this, I have a question, what is the auto-generated binding type on the client side when calling the service by adding service reference?
Look forward to your reply.
at the moment Iam working as a working student at a Software Company and I got the task to setup a client who works with a webservice from a third party (only have a wsdl-, xsd file and user certificate).
I read a lot about Webservices in the last time and I did a lot of tutorials, but I did not manage to connect to the Server and make a simple test request.
I have a Windowsform Application an added a Service reference to the project via the physical path of the wsdl document. From this the generated proxy classes.
The wsdl and xsd file you can find here [https://www.dropbox.com/sh/qgopygt9gtbhwq6/AADHp8k1ktfNrzMVKCjQ0EsPa?dl=0][1]
EndpointAddress ea = new EndpointAddress("https://212.62.77.106:9443/hapwebservices/secure_routed/dms");
DMSServiceClient client = new DMSServiceClient(new BasicHttpsBinding(), ea);
X509Certificate2 cert = new X509Certificate2(#"C:\Users\myName\Desktop\DMS-test-2016.p12", "privateKey");
client.ClientCredentials.ClientCertificate.Certificate = cert;
Header header = new Header();
header.InputTime = DateTime.Now;
header.SystemId ="TheSystemID";
header.OrganisationId = "TheOrganisationID";
header.Password = "Password";
header.OrganisationName = "Oraganisation";
header.InterfaceVersion="3.0";
header.DMSVersion = "1";
header.DMSName = "DMSNAME";
DateTime datetime = DateTime.Now;
client.test(header, ref datetime);
Above you see my Code to invoke the test Method. But I alway get the exception that the Server Certificate is probably not configured correctly with HTTP.SYS. Another Reason is a mismatch from Client and Server.
Can you help me with this issue? Have I set up the proxy classes correctly?
Many thanks in advance!
Regards Lars
I have a WCF service and a client that uses that service. They use WSHttpBinding with MTOM message encoding. The client doesn't use an app.config file, and does all of the endpoint configuration in code.
It all works rather nicely in a normal environment, however I now have some users who are attempting to connect to the service from behind an http proxy. Whenever they try to connect, they get a 407 (Proxy Authentication Required) warning.
I've managed to set up my own testing environment using a virtual machine with a private network that connects to a proxy, so I can simulate what they are seeing.
I've tried setting the system.net useDefaultCredentials property in app.config, but that doesn't seem to have any effect. I've examined the packets being sent, and they don't contain any Proxy-Authentication headers. Looking at web traffic through the proxy, they do use that header.
I've also tried hard coding the proxy server into the client, but that gives a "cannot connect to server" exception. Examining the packets, the client sends out 3 small ones to the proxy, none of which are an http request, and that's it. I'm not sure what it's doing there.
I even went so far as to add a message inspector to the client, and manually inject the required header into the requests, but that's not showing up in the header.
I'm hitting the end of my rope here, and I really need a solution. Any ideas on what I'm missing here, or a solution?
This ( WCF Service with wsHttpBinding - Manipulating HTTP request headers ) seems promising, but I'm still stuck.
EDIT:
Here's a portion of the code.
var binding = new WSHttpBinding();
binding.MaxReceivedMessageSize = 100000000;
binding.MessageEncoding = WSMessageEncoding.Mtom;
binding.ReaderQuotas.MaxArrayLength = 100000000;
binding.OpenTimeout = new TimeSpan(0, 2, 0);
binding.ReceiveTimeout = new TimeSpan(0, 2, 0);
binding.SendTimeout = new TimeSpan(0, 2, 0);
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
binding.UseDefaultWebProxy = true;
// I've also tried setting this to false, and manually specifying the binding.ProxyAddress
binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Basic;
var endpointAddress = new EndpointAddress(new Uri(hostUrl));
clientProxy_ = new UpdaterServiceProxy(binding, endpointAddress);
// this behavior was the attempt to manually add the Proxy-Authentication header
//clientProxy_.Endpoint.Behaviors.Add(new MyEndpointBehavior());
clientProxy_.ClientCredentials.UserName.UserName = userName;
clientProxy_.ClientCredentials.UserName.Password = password;
clientProxy_.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
System.ServiceModel.Security.X509CertificateValidationMode.ChainTrust;
// do stuff...
After a lot of experimentation I've made some progress. It turns out that I can manually specify the proxy, and it will work.
WebProxy proxy = new WebProxy("http://x.x.x.x:3128", false);
proxy.Credentials = new NetworkCredential("user", "pass");
WebRequest.DefaultWebProxy = proxy;
That code appears just before I instantiate my clientProxy_. I had tried this previously, but it silently failed because I hadn't specified the port. I still cannot get it to pick up the proxy settings specified in the Windows Internet Settings. I tried setting proxy.Credentials = CredentialCache.DefaultNetworkCredentials; but that also seemed to have no effect.
I'm also running into a problem now with the client trying to validate the service's certificate using ChainTrust, but the requests for the chained certificates are not using the proxy settings. Since this is a more specific question, I wrote it up separately here: Certificate validation doesn't use proxy settings for chaintrust
So I'm still hoping for more help.
UPDATE:
I ended up just adding a network configuration dialog to my application so the user could specify their proxy settings. I've been unable to get the automatic proxy settings to work properly.
I have a self-hosted WCF service that is hosted by a desktop application.
I can successfully connect to the service locally on my PC, but I can't use the service remotely, at least without providing my windows/domain level credentials.
I use the following code to start the service in the app:
ServiceHost host = new ServiceHost(
typeof (SMService),
new Uri("net.tcp://localhost:" + SMGlobals._DEFAULTSERVICEPORT.ToString() + "/SMService"));
host.AddServiceEndpoint(
typeof(ISMService),
new NetTcpBinding(),
"");
System.ServiceModel.Channels.Binding mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
var metadataBehavior =
new ServiceMetadataBehavior();
host.Description.Behaviors.Add(metadataBehavior);
host.AddServiceEndpoint(
typeof(IMetadataExchange),
mexBinding,
"net.tcp://localhost:" + SMGlobals._DEFAULTSERVICEPORT.ToString() + "/SMService/mex");
host.Open();
SMGlobals.SMServiceHost = host;
If I create a simple client to call the service using the following code:
var client = new SMServiceClient();
var uri = "net.tcp://192.168.11.10:8760/SMService";
client.Endpoint.Address = new EndpointAddress(uri);
var initiateResponse = client.InitiateAuthentication(new InitiateAuthenticationRequest());
MessageBox.Show("Success!");
I receive the following exception:
System.ServiceModel.Security.SecurityNegotiationException: The server has rejected the client credentials. ---> System.Security.Authentication.InvalidCredentialException: The server has rejected the client credentials. ---> System.ComponentModel.Win32Exception: The logon attempt failed
Now, from other research, I have discovered that I could provide my credentials with the client call using the following code:
var client = new SMServiceClient();
var uri = "net.tcp://192.168.11.10:8760/SMService";
client.Endpoint.Address = new EndpointAddress(uri);
client.ClientCredentials.Windows.ClientCredential.Domain = "domain";
client.ClientCredentials.Windows.ClientCredential.UserName = "my_user_name";
client.ClientCredentials.Windows.ClientCredential.Password = "my_password";
var initiateResponse = client.InitiateAuthentication(new InitiateAuthenticationRequest());
MessageBox.Show("Success!");
And now, the code successfully completes.
I'm having a hard time figuring out how to remove this requirement. I've tried messing around with the binding setup on the client without success.
Can anyone point me in the right direction?
A Tcp Binding has security enabled by default, so to get what you want, you need to explicitly turn it off. Add your endpoint like this. You might also explore the MSDN help for NetTcpBinding as you might want to user an alternate constructor to also switch off reliable messaging.
host.AddServiceEndpoint(
typeof(ISMService),
new NetTcpBinding(SecurityMode.None),
"");
Set the appropriate Authentication on the Binding.
ClientAuthenticationType="None"
I had a similar issue. Worked locally between two processes but the same code failed when the two processes were put on different machines (or locally using a public URL that resolved to the local machine, e.g. mylocalmachine.corp.com). I found that I needed to explicitly set the Anonymous binding's security to 'None':
<binding name="TcpAnonymousBinding" portSharingEnabled="true" receiveTimeout="24:00:00">
<security mode="None"/>
</binding>