HTTPS webservice using WCF - wcf

I try to connect to https web service over proxy at my end.
below is code snippet
Dim strProxyURL As String = "http://myproxy.com"
Dim mypingRequest As New pingRequest()
Dim httpUri As New Uri("https://mysite.com")
Dim mybinding As New WSHttpBinding()
Dim remoteAddress As New EndpointAddress(httpUri)
mybinding.UseDefaultWebProxy = True
mybinding.BypassProxyOnLocal = True
mybinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Windows
mybinding.MessageEncoding = WSMessageEncoding.Mtom
mybinding.TextEncoding = System.Text.Encoding.UTF8
mybinding.Security.Mode = SecurityMode.TransportWithMessageCredential 'TransportWithMessageCredential
mybinding.Security.Message.ClientCredentialType = MessageCredentialType.Windows
Dim myMBClient As New v1_PortTypeClient(mybinding, remoteAddress)
myMBClient.ClientCredentials.Windows.ClientCredential.UserName = "username"
myMBClient.ClientCredentials.Windows.ClientCredential.Password = "pwd"
myMBClient.ping()
when I use proxy I error proxy authentication required error
if I remove proxy from desktop and use direct internet then I go to site web service but cannot login even thought the gave correct username and password

issue is resolved. WCF web services uses Custom binding hence error. also i have add webrequest.defaultwebproxy and credentials to access via web proxy at requesting client side WCF Custom Http Proxy Authentication

Related

Using WCF in .net 2

I've got a method of connecting and use a WCF method, which is on HTTPS and requires a username and password in .net 4.
Now I need to do the same but within .Net 2 and I can't seem to get it to work. I keep on getting the below error. Can anyone help?
Error
{"The underlying connection was closed: An unexpected error occurred on a receive."}
Inner Exception
{"Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."}
.Net 4 Original Code:
WSHttpBinding myBinding = new WSHttpBinding();
myBinding.Security.Mode = SecurityMode.Transport;
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
EndpointAddress ea = new EndpointAddress(wcfURL);
var web = new Gateway.GatewayClient(myBinding, ea);
// var web = new Gateway.GatewayClient();
XMLCrypto crypto = new XMLCrypto();
web.ClientCredentials.UserName.UserName = crypto.DecryptString(username);
web.ClientCredentials.UserName.Password = crypto.DecryptString(password);
web.Open();
web.Inbound("HOLog", message.Trim().Replace("\n", "").Replace(#"\\", ""));
web.Close();
.Net 2 Code
XMLCrypto crypto = new XMLCrypto();
url = "http://..../gateway/gateway.svc";
userName = crypto.DecryptString(userName);
password = crypto.DecryptString(password);
var web = new Gateway.Gateway();
var credentials = new NetworkCredential(userName, password);
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(url), "Basic", credentials);
web.Credentials = credentials;
string returnMessage = web.Inbound("LSOA", " ");
After a long trolling over the web and testing different ways of talking to a WCF method, I have found the reason why it does not work.
Currently the WCF is set to use wsHttpBinding and now I know that .net 2, does not support it. My work around was to change the Binding from wsHttpBinding to basicHttpBinding within the Web.config of the WCF.
To do this and not effect anything using the WCF, I have to create a seprate Sub domain that will ref a WCF with the config that has the corrected Binding.
"The wsHttpBinding is not compatible with the ASMX-style web references used in .NET 2.0."
How to consume WCF wsHttpBinding Service in application built in 2.0?

WCF : Configuring message security programmatically

I'm coding an Azure WCF Service Bus service, which is to be configured programmatically to have message security using certificates:
ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Tcp;
// create the service URI based on the service namespace
Uri address = ServiceBusEnvironment.CreateServiceUri("sb", ConfigurationManager.AppSettings["serviceNamespace"], "TestService");
// create the credentials object for the endpoint
TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();
sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(ConfigurationManager.AppSettings["issuerName"], ConfigurationManager.AppSettings["issuerSecret"]);
//Create and bind the serviceEndpoint
ContractDescription contractDescription = ContractDescription.GetContract(typeof(ITestContract), typeof(TestServiceImpl));
ServiceEndpoint serviceEndPoint = new ServiceEndpoint(contractDescription);
serviceEndPoint.Address = new EndpointAddress(address);
var NetTcpRelayBinding = new NetTcpRelayBinding(EndToEndSecurityMode.TransportWithMessageCredential, RelayClientAuthenticationType.RelayAccessToken);
NetTcpRelayBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate; //The serivice will check the TrustedPeople store for the client
serviceEndPoint.Binding = NetTcpRelayBinding;
serviceEndPoint.Behaviors.Add(sharedSecretServiceBusCredential);
Host = new ServiceHost(typeof(TestServiceImpl), address);
//Add a service certificate
Host.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;
Host.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine,StoreName.My,X509FindType.FindByThumbprint,"E86870F0118CE39D771A49B9337C28444F3C7348");
// create the service host reading the configuration
Host.Description.Endpoints.Add(serviceEndPoint);
I can get this service up and running, however, any client )with just the ServiceBus SharedSecret, clientCredentials NOT set to use any cert) is able to call my service without any errors.
Is the above code sufficient to indicate that certificates (and only certificates base authorization) should be used for message security ?
Any good articles on configuring WCF message security programmatically ?
Turns out that lack of sleep was the culprit; I was running an older version of the service. Clients without any certificates do error out (with System.ServiceModel.ProtocolException was unhandled Message=Error while reading message framing format at position 1 of stream (state: Start).
A properly coded up client for this is :
ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Tcp;
string serviceNamespace = "valid-namespace";
string issuerName = "owner";
string issuerSecret = "validSecret";
// create the service URI based on the service namespace
Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "valid-namespace");
// create the credentials object for the endpoint
TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();
sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret;
sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName = issuerName;
sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = issuerSecret;
ChannelFactory<ITestChannel> channelFactory = new ChannelFactory<ITestChannel>();
channelFactory.Endpoint.Address = new EndpointAddress(serviceUri);
var NTRB = new NetTcpRelayBinding();
NTRB.Security.Mode = EndToEndSecurityMode.TransportWithMessageCredential;
NTRB.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
channelFactory.Endpoint.Binding = NTRB;
channelFactory.Endpoint.Contract.ContractType = typeof(ITestChannel);
// apply the Service Bus credentials
channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
//Question : Why doesn't use of the following line effect Service-Validation ? I can successfully call the service from a machine where the server's certificate does NOT exist in the trusted-people store
//channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.PeerTrust;
channelFactory.Credentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "valid-thubmprint");
// create and open the client channel
ITestChannel channel = channelFactory.CreateChannel();
Console.WriteLine(channel.ServiceMethod());
Console.ReadKey();
channel.Close();
channelFactory.Close();
Still have the problem of the ServiceCertificate always being assumed valid, even when PeerTrust is used for channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode and the service certificate isn't in the TrustedPeople store.
Anyone with ideas on why this happens ?

WCF: Passing Kerboros token via HTTP call instead of HTTPS

I want to pass Kerberos token via HTTP call to a server using WCF.
I have a piece of code that successfully does this. But it only works if I make a request to HTTPS URI.
var httpBinding = new WebHttpBinding(WebHttpSecurityMode.Transport) { MaxReceivedMessageSize = Int32.MaxValue };
httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
httpBinding.Security.Transport.Realm = "MyCompany.com";
var endPoint = new EndpointAddress("https:xxxxxxxx.com/my/service); // This works
var endPoint = new EndpointAddress("http:xxxxxxxx.com/my/service); // This does not work
var channelFactory = new ChannelFactory<IMyServiceContract>(httpBinding, endPoint);
channelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior());
_channel = channelFactory.CreateChannel();
_channel.ConsumeService();
If I make a request via the channel, and if the end point is https. It works and I can verify the Kerberos Token is in the HTTP requst.
If the service end point is HTTP, it gives error:
System.ArgumentException : The provided URI scheme 'http' is invalid; expected 'https'.
Parameter name: via
Can someone let me know how to Configure WCF so that it send Kerboros token with HTTP URI.
Regards,
Kevin
When you don't want to use HTTPS you must set your security mode to WebHttpSecurityMode.TransportCredentialOnly. If you use WebHttpSecurityMode.Transport it demands HTTPS.

Calling SharePoint Web Service over SSL in VB.Net (401 Unauthorized)

I'm trying to call the AddAttachment of the Lists.asmx SharePoint web service the below code works fine if I'm calling the web service over HTTP.
Dim img(MyFile.PostedFile.ContentLength - 1) As Byte
MyFile.PostedFile.InputStream.Read(img, 0, img.Length)
'Dim fStream As FileStream = File.OpenRead(FullFileName)
Dim fileName As String = MyFile.PostedFile.FileName.Substring(3)
Dim listService As New wsList.Lists()
Dim credentials As New System.Net.NetworkCredential(UserName, Password, Domain)
If Not SiteUrl.EndsWith("/") Then
SiteUrl += "/"
End If
SiteUrl += "_vti_bin/Lists.asmx"
'SiteUrl = SiteUrl.ToLower.Replace("http:", "https:")
listService.Url = SiteUrl
listService.Credentials = credentials
Dim addAttach As String = listService.AddAttachment(ListName, ItemId, fileName, img)
ReturnValue = True
However if I uncomment out this line
'SiteUrl = SiteUrl.ToLower.Replace("http:", "https:")
I will get the following error: The request failed with HTTP status 401: Unauthorized
Now if I leave the above line commented out AND then also comment out this line
listService.Credentials = credentials
I will get the same 401 error (expected) so it appears the credentials are being accepted correctly over HTTP but not HTTPS. Can one help explain this to me and have any thoughts on how to fix the issue?
Thanks in advance!
This morning I was working with one of our system guys. He checked some IIS logs and could see errors trying to access the web service over HTTPS. He went into Central Admin and added some Alternate Access Mappings to include the HTTPS urls. Then everything worked!

Accessing HTTPS site through Proxy Server

I am adding code to use a proxy server to access the Internet.
The code works fine when requesting a file from a normal (HTTP) location, but does not work when accessing a secure location (HTTPS).
This is the code that works just fine:
URL = "http://UnSecureSite.net/file.xml"
Dim wr As HttpWebRequest = CType(WebRequest.Create(URL), HttpWebRequest)
Dim proxy As System.Net.IWebProxy
proxy = WebRequest.GetSystemWebProxy
wr.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim ws As HttpWebResponse = CType(wr.GetResponse(), HttpWebResponse)
// (more work here)
As soon as I change the URL to go to HTTPS, I get a 407 returned to me.
Anyone have any ideas?
URL = "https://SecureSite.net/file.xml"
Dim wr As HttpWebRequest = CType(WebRequest.Create(URL), HttpWebRequest)
Dim proxy As System.Net.IWebProxy
proxy = WebRequest.GetSystemWebProxy
wr.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim myCache As New CredentialCache()
myCache.Add(New Uri("https://SecureSite.net"), "Basic", New NetworkCredential(UserName, Password))
wr.Credentials = myCache
Dim ws As HttpWebResponse = CType(wr.GetResponse(), HttpWebResponse)
// (more work here)
A HTTPS request through a web-proxy is different from a standard HTTP request. A regular HTTP request will use the GET method. However, a HTTPS request needs to use a CONNECT method. Then, the proxy will merely establish a tunnel to the server. Subsequent messages will be sent directly between the client and the server through the proxy tunnel. The proxy has no way of interpreting the data flowing in between.
Under normal situations:
Client -+- [CONNECT] ---> Proxy --- [DIRECT TCP] -+-> Server
| | |
+-------------[ENCRYPTED TCP]-------------+
I am not familiar enough with the VB code to know if that is what is happening. However, I suspect that it is not. The easiest way to check is to intercept the message being sent to the proxy. Make sure that it begins with a "CONNECT ...".