C# BasicHttpBinding with BasicHttpSecurityMode.Transport for Silverlight client - c#

i want to secure a Silverlight App with SSL.
So I try to wrote a proof of concept, where I host two BasicHttpBindings. One with BasicHttpSecurityMode.None and the other with BasicHttpSecurityMode.Transport.
But I not able to get the second one running, The WCFTestClient from VS Tools display this error message
// Error: Cannot obtain Metadata from https://localhost:8081/ If this is
// a Windows (R) Communication Foundation service to which you have
// access, please check that you have enabled metadata publishing at the
// specified address. For help enabling metadata publishing, please
// refer to the MSDN documentation at
// http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange
// Error URI: https://localhost:8081/ Metadata contains a reference
// that cannot be resolved: 'https://localhost:8081/'. An error
// occurred while making the HTTP request to https://localhost:8081/.
// This could be due to the fact that the server certificate is not
// configured properly with HTTP.SYS in the HTTPS case. This could also
// be caused by a mismatch of the security binding between the client and
// the server. The underlying connection was closed: An unexpected
// error occurred on a send. Unable to read data from the transport
// connection: An existing connection was forcibly closed by the remote
// host. An existing connection was forcibly closed by the remote
// hostHTTP GET Error URI: https://localhost:8081/ There was an
// error downloading 'https://localhost:8081/'. The underlying
// connection was closed: An unexpected error occurred on a send.
// Unable to read data from the transport connection: An existing
// connection was forcibly closed by the remote host. An existing
// connection was forcibly closed by the remote host
I would be great if some could view over my code, I stuck for two days with this. It need to be done all programmatically.
Thanks a lot.
Almost the whole programm: http://pastebin.com/9j9K43tS
The Endpoints
private static readonly Uri UriBase = new Uri("http://localhost:8080/");
private static readonly Uri UriBaseService = new Uri("http://localhost:8080/Basic");
private static readonly Uri UriSecure = new Uri("https://localhost:8081/");
private static readonly Uri UriSecureService = new Uri("https://localhost:8081/Secure");
This Works
private static void BasicHTTPServer()
{
var binding = new BasicHttpBinding();
binding.Name = "binding1";
binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
binding.Security.Mode = BasicHttpSecurityMode.None;
// Create a ServiceHost for the CalculatorService type and provide the base address.
_serviceHost = new ServiceHost(typeof (ServiceBasic), UriBase);
_serviceHost.AddServiceEndpoint(typeof (IServiceBasic), binding, UriBaseService);
_serviceHost.AddServiceEndpoint(typeof (IPolicyRetriever), new WebHttpBinding(), "")
.Behaviors.Add(new WebHttpBehavior());
var smb = new ServiceMetadataBehavior {HttpGetEnabled = true, HttpGetUrl = UriBase};
_serviceHost.Description.Behaviors.Add(smb);
// Open the ServiceHostBase to create listeners and start listening for messages.
_serviceHost.Open();
Logger.Log(Server.Basic, string.Format("Open at {0} Service: {1}", UriBase, UriBaseService));
}
This doesn't Works
private static void SecureHTTPServer()
{
var binding = new BasicHttpBinding();
// it doesnt matter if I use BasicHttpsBinding or BasicHttpBinding
binding.Name = "binding2";
binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
// Create a ServiceHost for the CalculatorService type and provide the base address.
_serviceHostSecure = new ServiceHost(typeof (ServiceBasic), UriSecure);
_serviceHostSecure.Credentials.ServiceCertificate.Certificate = GetCertificate();
//load a certificate from file
_serviceHostSecure.Credentials.ClientCertificate.Authentication.CertificateValidationMode =
X509CertificateValidationMode.None;
_serviceHostSecure.AddServiceEndpoint(typeof (IServiceBasic), binding, UriSecureService);
var webHttpBinding = new WebHttpBinding(WebHttpSecurityMode.Transport);
webHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
_serviceHostSecure.AddServiceEndpoint(typeof (IPolicyRetriever), webHttpBinding, "")
.Behaviors.Add(new WebHttpBehavior());
var smb = new ServiceMetadataBehavior {HttpsGetEnabled = true, HttpsGetUrl = UriSecure};
_serviceHostSecure.Description.Behaviors.Add(smb);
// Open the ServiceHostBase to create listeners and start listening for messages.
_serviceHostSecure.Open();
Logger.Log(Server.Basic, string.Format("Open at {0} Service: {1}", UriSecure, UriSecureService));
}

Related

How to setup proxy Credentials using HttpTransportBindingElement on WCF?

I coded a WCF Service using HttpTransportBindingElement in conjunction with IIS on port 80.
The code works fine as long as no proxy is used. But if a customer has a http-proxy the communication between WCF-Client and Server does not work in this case by occuring following error:
'There was no endpoint listening at ... that could accept the message. This is often caused by an incorrect address or SOAP action.'
It is essential to use settings by code ONLY!
here is my code approach for that issue but i stuck on it:
bool SendClientRequest(Action<ICustomerService> channel)
{
string proxy ="my.proxy.domain:8080";
string user = "user1";
string password="secret";
// maybe i do not need this 3 lines!
WebProxy webproxy = new WebProxy(proxy, true);
webproxy.Credentials = new NetworkCredential(user, password);
WebRequest.DefaultWebProxy = webproxy;
CustomBinding customBinding = new CustomBinding();
customBinding.Elements.Add(new HttpTransportBindingElement()
{
AuthenticationSchemes.None : AuthenticationSchemes.Basic,
ProxyAddress = string.IsNullOrEmpty(proxy) ? null : new Uri(proxy),
UseDefaultWebProxy = false,
BypassProxyOnLocal = true,
TransferMode = TransferMode.Streamed,
MaxReceivedMessageSize = 84087406592,
MaxBufferPoolSize = 0x1000000,
MaxBufferSize = 0x1000000
});
using (ChannelFactory<ICustomerService> factory = new
ChannelFactory<ICustomerService>(customBinding ))
{
IClientChannel contextChannel = null;
string url = "http://my.domain.de/Distribution/eService.svc",
EndpointAddress ep = new EndpointAddress(url);
ICustomerService clientChannel = factory.CreateChannel(ep);
contextChannel = clientChannel as IClientChannel;
contextChannel.OperationTimeout = TimeSpan.FromMinutes(rcvTimeout );
channel(clientChannel); // <- here i get the exception!
return true;
}
}
I tried several solution approaches but nothing seems to be specific like mine.
I think you have a few options, some of which I'll detail below.
First you could set UseDefaultWebProxy to true. This would then mean that proxy information is retrieved automatically from system proxy settings, configurable in Internet Explorer (Internet Options > Connections > LAN settings > Proxy server). This may be appropriate if you don't need to specify credentials for proxy use.
Another approach that's worked for me is to use the ProxyAuthenticationScheme property within your HttpTransportBindingElement() object. This property is only available on the CustomBinding class and allows an authentication scheme to be specified that will be used to authenticate against a proxy. In conjunction with this, the proxy server must be set against property ProxyAddress. Last but not least, the credentials to use against the proxy should be set according to the authentication scheme used, so for example, using AuthenticationSchemes.Ntlm would mean setting the UserName and Password properties on ChannelFactory.ClientCredentials.Windows.ClientCredential or perhaps ChannelFactory.ClientCredentials.HttpDigest.ClientCredential
With the second approach, be sure to note the difference between holding credentials in the ChannelFactory for use with the remote service versus credentials used for the proxy server. I've highlighted these in the code example below for clarity:
// Example service call using a CustomBinding that is configured for client
// authentication based on a user name and password sent as part of the message.
var binding = new CustomBinding();
TransportSecurityBindingElement securityBindingElement = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
var secureTransport = new HttpsTransportBindingElement();
secureTransport.UseDefaultWebProxy = false;
secureTransport.ProxyAddress = new Uri("http://some-proxy");
secureTransport.ProxyAuthenticationScheme = AuthenticationSchemes.Ntlm;
binding.Elements.Add(securityBindingElement);
binding.Elements.Add(secureTransport);
var endpointAddress = new EndpointAddress("https://some-service");
var factory = new ChannelFactory<IService>(binding, endpointAddress);
// Credentials for authentication against the remote service
factory.Credentials.UserName.UserName = "serviceUser";
factory.Credentials.UserName.Password = "abc";
// Credentials for authentication against the proxy server
factory.Credentials.Windows.ClientCredential.UserName = "domain\user";
factory.Credentials.Windows.ClientCredential.Password = "xyz";
var client = factory.CreateChannel();
client.CallMethod();

How to work with WCF wsHttpBinding and SSL?

I need to develop a WCF Hosted in a console app WebService.
I made it work using the Mutual Certificate (service and client) method using SecurityMode.Message.
But now i need to change the Security Mode to SecurityMode.Transport and use the wsHttpBinding with SSL. I made this code to host the service but i cannot get the wsdl with the browser, or execute some webmethod in the console app client.
static void Main()
{
var httpsUri = new Uri("https://localhost:8089/HelloServer");
var binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
var host = new ServiceHost(typeof(WcfFederationServer.HelloWorld), httpsUri);
host.AddServiceEndpoint(typeof(WcfFederationServer.IHelloWorld), binding, "", httpsUri);
var mex = new ServiceMetadataBehavior();
mex.HttpsGetEnabled = true;
host.Description.Behaviors.Add(mex);
// Open the service.
host.Open();
Console.WriteLine("Listening on {0}...", httpsUri);
Console.ReadLine();
// Close the service.
host.Close();
}
The service is up, but i cannot get nothing on the https://localhost:8089/HelloServer.
On fiddler the get request via browser shows me this message:
fiddler.network.https> HTTPS handshake to localhost failed. System.IO.IOException
What im missing here?
Thanks
EDIT:
The Console Application Client Code
static void Main()
{
try
{
var client = new HelloWorldHttps.HelloWorldClient();
client.ClientCredentials.ClientCertificate.SetCertificate(
StoreLocation.LocalMachine,
StoreName.TrustedPeople,
X509FindType.FindBySubjectName,
"www.client.com");
Console.WriteLine(client.GetData());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
Getting this error:
Could not establish trust relationship for the SSL/TLS secure channel
When it comes to the service, you need to map the certificate to the specific port as described here
http://msdn.microsoft.com/en-us/library/ms733791(v=vs.110).aspx
As for the client, you need to skip the verification of certificate properties like valid date, the domain by relaxing the certificate acceptance policy. An easiest way would be to accept any certiticate
ServicePointManager.ServerCertificateValidationCallback = (a,b,c,d) => true
You can finetune the acceptance callback according to the docs to best fit your needs.

Changing from BasicHTTPBinding to BasicHTTPSBinding not working

I have a WCF service app and client app that I have written. I have been using BasicHTTPBinding on both ends.
To be clear: This is NOT a web application. The service is self-hosted in a PC application (NOT IIS). All configuration of the endpoints on both the client and server are done in code, not in app.config. In fact, to make sure, I have commented out the entire System.Servicemodel sections of app.config for both the client and server applications, and everything works great. This is all using BasicHTTPBinding.
Now, I want to change everything to use HTTPS instead of HTTP, for security reasons. I have changed what I thought I needed to change in my code, but it's not working.
Original Code (This works fine!)
Server:
BasicHttpBinding _binding;
Service1 _generalService;
ServiceHost _generalHost;
_binding = new BasicHttpBinding();
_binding.MaxReceivedMessageSize = 1000000;
_generalService = new Service1(_dbConnParams, _imagePath, _registrationProvider, LicenseCount);
_generalHost = new ServiceHost(_generalService, new Uri("http://localhost:8000"));
_generalHost.AddServiceEndpoint(typeof(IService1), _binding, "Service1");
_generalHost.Open();
Client:
internal static ToOrson.IService1 SetupService(string ServerAddress, TimeSpan? timeout = null)
{
var myBinding = new BasicHttpBinding();
myBinding.MaxReceivedMessageSize = 1000000;
if (timeout != null)
myBinding.SendTimeout = (TimeSpan)timeout;
string fullAddress = string.Format("http://{0}:8000/Service1", ServerAddress);
var myEndpoint = new EndpointAddress(fullAddress);
var myChannelFactory = new ChannelFactory<ToOrson.IService1>(myBinding, myEndpoint);
return myChannelFactory.CreateChannel();
}
private async void TestButton_Click(object sender, RoutedEventArgs e)
{
var TestService = MainWindow.SetupService(ServerBox.Text);
try
{
await TestService.TestConnectionAsync();
}
catch (Exception connException)
{
MessageBox.Show("Connection failed: " + connException.Message, "Error");
return;
}
MessageBox.Show("Connection succeeded!", "Success");
}
Code modified for HTTPS (This does NOT work)
Server:
BasicHttpsBinding _binding;
Service1 _generalService;
ServiceHost _generalHost;
_binding = new BasicHttpsBinding();
_binding.MaxReceivedMessageSize = 1000000;
_generalService = new Service1(_dbConnParams, _imagePath, _registrationProvider, LicenseCount);
_generalHost = new ServiceHost(_generalService, new Uri("https://localhost:8000"));
_generalHost.AddServiceEndpoint(typeof(IService1), _binding, "Service1");
_generalHost.Open();
Client:
internal static ToOrson.IService1 SetupService(string ServerAddress, TimeSpan? timeout = null)
{
var myBinding = new BasicHttpsBinding();
myBinding.MaxReceivedMessageSize = 1000000;
if (timeout != null)
myBinding.SendTimeout = (TimeSpan)timeout;
string fullAddress = string.Format("https://{0}:8000/Service1", ServerAddress);
var myEndpoint = new EndpointAddress(fullAddress);
var myChannelFactory = new ChannelFactory<ToOrson.IService1>(myBinding, myEndpoint);
return myChannelFactory.CreateChannel();
}
private async void TestButton_Click(object sender, RoutedEventArgs e)
{
var TestService = MainWindow.SetupService(ServerBox.Text);
try
{
await TestService.TestConnectionAsync();
}
catch (Exception connException)
{
MessageBox.Show("Connection failed: " + connException.Message, "Error");
return;
}
MessageBox.Show("Connection succeeded!", "Success");
}
Basically, I just changed BasicHTTPBinding to BasicHTTPSBinding and HTTP:// to HTTPS:// in all places in the code.
Here is the exception that I'm getting:
System.ServiceModel.CommunicationException "An error occurred while
making the HTTP request to https://localhost:8000/Service1. This could
be due to the fact that the server certificate is not configured
properly with HTTP.SYS in the HTTPS case. This could also be caused by
a mismatch of the security binding between the client and the server."
This exception is occurring on the client, on the call to TestService.TestConnectionAsync() (which is one of my OperationContracts).
Here are the inner exceptions:
System.Net.WebException "The underlying connection was closed: An
unexpected error occurred on a send."
System.IO.IOException "Unable to read data from the transport
connection: An existing connection was forcibly closed by the remote
host."
System.Net.Sockets.SocketException "An existing connection was
forcibly closed by the remote host"
Yes, I updated my service reference after these changes. Yes, I am targeting the .NET 4.5 framework. I don't think it's a firewall issue, as I'm using the same port (8000) in both cases, and I already have that port open.
What am I doing wrong?

The socket connection was aborted in wcf

i had created dynamic endpoint in server side and that endpoint used by client side.
Server side Code:
for (int i = 1; i <= 3; i++)
{
host.AddServiceEndpoint(typeof(PokerService.IPlayerService),
new NetTcpBinding(),
#"net.tcp://localhost:5054/player" + i);
}
Client side:
NetTcpBinding binding = new NetTcpBinding(SecurityMode.Message);
binding.Name = "NetTcpBinding_IPlayerService";
binding.Security.Message.ClientCredentialType = MessageCredentialType.IssuedToken;
EndpointAddress myEndpointAdd = new EndpointAddress(new Uri("net.tcp://localhost:5054/player1"),
EndpointIdentity.CreateDnsIdentity("pident.cloudapp.net"));
var PlayerChannelFactory = new DuplexChannelFactory<ClientApplication.PlayerService.IPlayerService>(new PlayerHandler(handler, this), binding, myEndpointAdd);
but it give error in this following line :
Player loggedIn = PlayerServiceProxy.Login("testuser" + Guid.NewGuid().ToString());
The error is:
"The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9870000'."
have anyone idea?
It seems like timeout. Review your client and service timeouts configuration.
Also, try to use svcTraceViewer.exe to review wcf trace

The provided URI scheme 'net.tcp' is invalid; expected 'http'

I'm a newbie at WCF. I'm trying to edit existing code to use a net.tcp binding instead of a http binding. I have done this easily in test projects using the config files, but for various reasons, in the real project it is done programatically.
I made the necessary changes, and the service host seems to start correctly:
Uri baseAdress= new Uri("net.tcp://localhost:7005/MyService/");
host = new ServiceHost(typeof(MyServiceImpl), baseAdress);
host.AddServiceEndpoint(
typeof(MyService),
new NetTcpBinding(),
"");
ServiceMetadataBehavior metadataBehavior;
metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (metadataBehavior == null)
{
metadataBehavior = new ServiceMetadataBehavior();
host.Description.Behaviors.Add(metadataBehavior);
}
BindingElement bindingElement = new TcpTransportBindingElement();
CustomBinding binding = new CustomBinding(bindingElement);
host.AddServiceEndpoint(typeof(IMetadataExchange), binding, "mex");
host.Open();
So far so good. I edited the connection string client side:
string serverUri = string.Format("net.tcp://{0}:{1}/MyService", serverName, port);
MyService server = new MyServiceClient("MYS", serverUri);
But when i try to call functions from my service, i get this error:
The provided URI scheme 'net.tcp' is invalid; expected 'http'
Not quite sure what i am missing... Any hints?

Categories