Error while accessing Custom STS(WCF Service) on Azure - c#

I've a custom STS having active federation endpoint that works well on local box.
Local Url is "https://localhost/CustomIDP/Service.svc"
After hosting on Azure on the final step of acquiring SAML token I am getting the following error while acquiring token from STS:
[System.ServiceModel.CommunicationException]
{"An error occurred while receiving the HTTP response to "https://mysts.cloudapp.net/Service.svc". This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details."}
InnerException:
[System.Net.WebException]: {"The underlying connection was closed: An unexpected error occurred on a receive."}
InnerException:
[System.IO.IOException]:{"Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."}
InnerException:
[System.Net.Sockets.SocketException]: {"An existing connection was forcibly closed by the remote host"}: at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
Appreciate any inputs. Please find below the code snippet used for calling the STS for acquiring SAML token. The error occurs at channel.Issue statement.
using (var factory = new WSTrustChannelFactory(
new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
new EndpointAddress(new Uri(stsEndpoint))))
{
factory.Credentials.UserName.UserName = username;
factory.Credentials.UserName.Password = password;
factory.TrustVersion = TrustVersion.WSTrust13;
WSTrustChannel channel = null;
try
{
var rst = new RequestSecurityToken
{
RequestType = WSTrust13Constants.RequestTypes.Issue,
AppliesTo = new EndpointAddress(realm),
KeyType = KeyTypes.Bearer,
};
channel = (WSTrustChannel)factory.CreateChannel();
return channel.Issue(rst);
}
finally
{
if (channel != null)
{
channel.Abort();
}
factory.Abort();
}
}
Service Configuration for STS service hosted on Azure:
<system.serviceModel>
<services>
<service name="Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceContract" behaviorConfiguration="ServiceBehavior">
<endpoint address="" binding="ws2007HttpBinding" contract="Microsoft.IdentityModel.Protocols.WSTrust.IWSTrust13SyncContract" bindingConfiguration="ws2007HttpBindingConfiguration"/>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<ws2007HttpBinding>
<binding name="ws2007HttpBindingConfiguration">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName" establishSecurityContext="false" />
</security>
</binding>
</ws2007HttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceCredentials>
<serviceCertificate x509FindType="FindByThumbprint" findValue="[thumbprint]" storeLocation="LocalMachine" storeName="My" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<microsoft.identityModel>
<service>
<!-- User name and password are not authenticated by windows authentication but a custom verification is done -->
<securityTokenHandlers>
<remove type="Microsoft.IdentityModel.Tokens.WindowsUserNameSecurityTokenHandler, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add type="ActiveIdPSite.CustomUserNameSecurityTokenHandler, ActiveIdPSite" />
</securityTokenHandlers>
<serviceCertificate>
<certificateReference x509FindType="FindByThumbprint" findValue="[thumbprint]" storeLocation="LocalMachine" storeName="My" />
</serviceCertificate>
<certificateValidation certificateValidationMode="None" />
</service>
</microsoft.identityModel>

The issue is solved. Root cause was related to certificates.
1.Enable WCF Diagnostics while deploying.
2.Get the svclog file and open with Microsoft Service Trace viewer.
Here's the extract from svclog.
Replying to an operation threw a exception:
System.NotSupportedException - The private key is not present in the X.509 certificate
Since the certificate didn't have private key in exportable format, it failed to read the private key.
Used the fix mentioned here:
http://social.msdn.microsoft.com/Forums/en/Geneva/thread/2b2681af-838e-4f22-84fa-b5494b9dcc02

Related

WCF on .NET Core missing client Negotiate scheme in authorization scheme

After I moved WCF service and ASP.NET Core website to server I get following error:
The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate, NTLM'.
I have enabled only Windows Authentication on WCF service with following web.config:
<system.serviceModel>
<client />
<behaviors>
<serviceBehaviors>
<behavior name="authBehavior">
<serviceAuthorization principalPermissionMode="UseWindowsGroups">
<authorizationPolicies>
<add policyType="WCF.AuthorizationPolicy, WCF" />
</authorizationPolicies>
</serviceAuthorization>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCF.IdentityValidator, WCF" />
<serviceCertificate findValue="16E86CCAFFE6211DAE6E841B984F71FB7609D349" storeLocation="LocalMachine" x509FindType="FindBySerialNumber" storeName="My" />
</serviceCredentials>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpsBinding>
<binding name="basicHttpsEndpointBinding" maxReceivedMessageSize="1073741824" maxBufferSize="1073741824" maxBufferPoolSize="1073741824">
<readerQuotas maxDepth="32" maxArrayLength="1073741824" maxStringContentLength="1073741824" />
<security mode="Transport">
<transport clientCredentialType="Ntlm" />
</security>
</binding>
</basicHttpsBinding>
</bindings>
<services>
<service name="WCF.MyService" behaviorConfiguration="authBehavior">
<endpoint address="" binding="basicHttpsBinding" bindingConfiguration="basicHttpsEndpointBinding" contract="WCF.IMyService">
<identity>
<dns value="example.com" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
ASP.NET Core client:
BasicHttpsBinding binding = new BasicHttpsBinding
{
MaxBufferPoolSize = 1073741824,
MaxBufferSize = 1073741824,
MaxReceivedMessageSize = 1073741824
};
binding.ReaderQuotas.MaxDepth = 32;
binding.ReaderQuotas.MaxArrayLength = 1073741824;
binding.ReaderQuotas.MaxStringContentLength = 1073741824;
binding.Security.Mode = BasicHttpsSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
MyServiceClient client = new MyServiceClient(binding, new EndpointAddress(new Uri("https://example.com/MyService.svc"), new DnsEndpointIdentity("mydomain.com")));
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
client.ClientCredentials.Windows.ClientCredential.Domain = Configuration.GetSection("WCF")["MyServiceDomain"];
client.ClientCredentials.Windows.ClientCredential.UserName = Configuration.GetSection("WCF")["MyServiceUserName"];
client.ClientCredentials.Windows.ClientCredential.Password = Configuration.GetSection("WCF")["MyServicePassword"];
// client call
I run out of ideas what could be wrong. If I change Ntlm to Windows in config/code then I get error with client authentication scheme 'Negotiate'. Can I somehow use both or I have to remove somehow Negotiate/Ntlm from IIS?
Thanks for any idea!
SOLUTION!
Method 1 from article https://blogs.msdn.microsoft.com/distributedservices/2009/11/10/wcf-calling-wcf-service-hosted-in-iis-on-the-same-machine-as-client-throws-authentication-error/
Requires server reboot!
I found this article which offers solution for my issue
Article: https://blogs.msdn.microsoft.com/distributedservices/2009/11/10/wcf-calling-wcf-service-hosted-in-iis-on-the-same-machine-as-client-throws-authentication-error/
Use method 1. Requires server reboot!
In registry I used CNAME like
mySubdomain
mySubdomain.myDomain.com
localhost
192.168.0.xxx
192.168.0.1 (default gateway)
xx.xx.xx.xx (my ip address)

WCF client in a universal app

Is it possible to call a WCF service from a universal application?
I added a service reference and the proxy was generated just fine.
But when creating a NetTcpBinding programmatically and passing that to the proxy's constructor the service model throws the exception PlatformNotSupported.
Both running the app in the simulator and on the local machine generates the same exception.
An exception of type 'System.PlatformNotSupportedException' occurred
in System.Private.ServiceModel.dll but was not handled in user code
"this operation is not supported"
EndpointAddress address = new EndpointAddress("net.tcp://test:9000/ServicesHost/PublishService");
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.None;
PublishingService.PublishClient proxy = new PublishingService.PublishClient(binding, address);
Does anybody have an example of a working WCF client in a UAP?
EDIT
It has something to do with the service being a duplex service!
The original contract:
[ServiceContract(CallbackContract = typeof(IPublishCallback))]
public interface IPublish { }
After removing the CallbackContract attribute the UAP client can create a connection, so basic WCF works.
So I guess it's better to rephrase the question.
Is it possible to create a duplex WCF client in a universal application?
edit servicemodel for the host
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="netTcpPublishService" openTimeout="00:00:10" receiveTimeout="infinite">
<reliableSession inactivityTimeout="24.20:31:23.6470000" enabled="true" />
<security mode="Transport">
<transport clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehaviour">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="serviceBehaviour" name="PublishService.Publish">
<endpoint binding="mexHttpBinding" name="mexPublishService"
contract="IMetadataExchange" />
<endpoint address="PublishService" binding="netTcpBinding" bindingConfiguration="netTcpPublishService"
name="netTcpPublishService" contract="PublishService.IPublish" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8004/ServicesHost/PublishService" />
<add baseAddress="net.tcp://localhost:9004/ServicesHost/PublishService" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
Yes, it is possible. This is how i connect in a sample app i did a while ago:
using Tradeng.Srvc.Client.WinAppSimple.SrvcRefTradeng;
private InstanceContext instanceContext;
private TradengSrvcClientBase serviceProxy;
instanceContext = new InstanceContext(this);
serviceProxy = new TradengSrvcClientBase(instanceContext);
bool result = await serviceProxy.ConnectAsync();
if (result)
{
// connected...
}
I used the binding from the config file that is generated when you add a reference to your service.
This is what the app looks like. Cutting edge stuff.... :O)
https://www.youtube.com/watch?v=YSg6hZn1DpE
The service itself is running as a WebRole on Azure, by the way.

WCF Service over SSL Could not establish secure channel for SSL/TLS with authority 'test-service.hostname.com'

I am having an issue. We are trying to attach a client certifacte to a WCF service over SSL required. When I try to navigate to the service through a browser it will show me the 'You have created a service page' but only if I attach the certificate, So I dont think its an IIS issue.
I have been through a ton of stack overflow questions and I think each time i make a little progress. But For the life of me I can not shake this issue. I added logging and here is what I am seeing for Errors:
System.Net Information: 0 : [12444] SecureChannel#15775260 - Certificate
is of type X509Certificate2 and contains the private key.
System.Net Information: 0 : [12444] AcquireCredentialsHandle(package = Microsoft Unified Security Protocol Provider, intent = Outbound, scc = System.Net.SecureCredential)
System.Net Error: 0 : [12444] AcquireCredentialsHandle() failed with error 0X8009030D.
System.Net Information: 0 : [12444] AcquireCredentialsHandle(package =
Microsoft Unified Security Protocol Provider, intent = Outbound, scc = System.Net.SecureCredential)
System.Net Error: 0 : [12444] AcquireCredentialsHandle() failed with error 0X8009030D.
System.Net.Sockets Verbose: 0 : [8000] Socket#13431269::Dispose()
System.Net Error: 0 : [8000] Exception in HttpWebRequest#55386345:: - The request was aborted: Could not create SSL/TLS secure channel..
System.Net Error: 0 : [8000] Exception in HttpWebRequest#55386345::GetResponse - The request was aborted: Could not create SSL/TLS secure channel..
System.ServiceModel Error: 131075 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error"><TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier><Description>Throwing an exception.</Description><AppDomain>/LM/W3SVC/1/ROOT/Application.TestHarness.Blah-1-130676061695261461</AppDomain><Exception><ExceptionType>System.ServiceModel.Security.SecurityNegotiationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Could not establish secure channel for SSL/TLS with authority 'test-bolt.homesite.com'.</Message><StackTrace> at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp; msgData, Int32 type)
at Application.TestHarness.IntegrationService.QuickQuote()
Service Config :
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="WebBehavior">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="Service.Namwe" behaviorConfiguration="WebBehavior">
<endpoint address=""
binding="wsHttpBinding"
bindingConfiguration="transportSecurity"
contract="Service.IContract"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="transportSecurity">
<security mode="Transport">
<transport clientCredentialType="Certificate"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
Client Config :
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="transportSecurity">
<security mode="Transport">
<transport clientCredentialType="Certificate"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name ="defaultClientCertificate">
<clientCredentials>
<clientCertificate storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" findValue="hostname.com"/>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint name="boltService" behaviorConfiguration="defaultClientCertificate"
address="https://hostname.com/Service/Integration.svc"
binding="wsHttpBinding"
bindingConfiguration="transportSecurity"
contract="ServiceRef.IServiceContract" />
</client>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
Any advice would be greatly appreciated.
I figured out what my issue was. The App pool that was running the service did not have access to the certificate. I was assuming since I had stuck it in IIS that all app pools would have access (not the case). In case anyone finds this and has a simialar issue here is what i eventually found and what fixed it.
https://msdn.microsoft.com/en-us/library/aa702621.aspx You can also do this in MMC if you like the GUI more than cmd line tools.
I have same problem and solved problem with this code;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
Or try this code
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
Running visual studio in administrator mode fixed this issue for me.

Validate Oauth Access Token in WCF Message Inspector

I have a client (could be C# or PHP) that needs to be able to request an OAuth 2.0 access token (JWT for compatibility) from my STS (Thinktecture Identity Server), and then send that token to a webhttp endpoint in a WCF Service. The service will validate the token in a message inspector, and either throw an error or continue to a service method. I am using Thinktecture Identity Model, and RestSharp to send rest requests.
So far here is what I have:
Client:
var client = new OAuth2Client(
new Uri("https://mysts/issue/oauth2/token"),
"client",
"secret");
var response = client.RequestAccessTokenUserName("username", "password", "http://localhost:51696/");
var token = response.AccessToken;
var restClient = new RestClient("https://127.0.0.1:444/");
var restRequest = new RestRequest(Method.POST);
restRequest.AddHeader("Authorization", token);
restRequest.AddObject(new Request());
And I get the access token from the sts just fine, I'm not sure if I'm inserting the token in the authorization header correctly or not.
Message inspector:
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
#region new code
string binding = OperationContext.Current.EndpointDispatcher.ChannelDispatcher.BindingName;
if (binding == "http://tempuri.org/:SecureRestBinding")
{
// Check to see if there is an Authorization in the header, otherwise throw a 401
if (WebOperationContext.Current.IncomingRequest.Headers["Authorization"] == null)
{
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"myrealm\"");
throw new WebFaultException<string>("No username or password was provided", HttpStatusCode.Unauthorized);
}
else
{
//Code to validate oauth token?
}
}
This makes sure to only check REST messages, SOAP messages are handled via a security token handler. I need to fill in code to validate the oauth token, but I cant seem to find a good example anywhere.
web.config in case its relevant:
<system.serviceModel>
<services>
<service behaviorConfiguration="MyServiceBehavior" name="MyWCFWebRole.MyWcfService">
<endpoint address="/REST/"
behaviorConfiguration="MyRestBehavior"
binding="webHttpBinding" bindingConfiguration="RESTSSLBinding"
name="RestSSLEndpoint" bindingName="SecureRestBinding"
contract=MyWCFWebRole.MyWcfServic" />
<endpoint address="/SOAP/"
binding="basicHttpBinding"
bindingConfiguration="secureHttpBinding"
name="SecureHttpEndpoint"
bindingName="SecureHttpBinding"
contract="MyWCFWebRole.MyWcfServic" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="RESTSSLBinding">
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
</binding>
</webHttpBinding>
<basicHttpBinding>
<binding name="secureHttpBinding">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
<ws2007FederationHttpBinding>
<binding name="">
<security mode="Message">
<message>
<issuerMetadata address="mex_address" />
</message>
</security>
</binding>
</ws2007FederationHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="MyRestBehavior">
<webHttp helpEnabled="true" faultExceptionEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="MyServiceBehavior">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceAuthorization principalPermissionMode="Always" />
<serviceCredentials useIdentityConfiguration="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment minFreeMemoryPercentageToActivateService="0" aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<protocolMapping>
<add scheme="http" binding="ws2007FederationHttpBinding" />
</protocolMapping>
</system.serviceModel>
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="MyService.svc" />
</files>
</defaultDocument>
<modules runAllManagedModulesForAllRequests="true" />
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="false" />
</system.webServer>
Any help is appreciated. Using .net 4.5

WCF https with only server certificate

I trying to do WCF using self-signed certificate. I found some solutions,but they need client to know clinet certificate before connection.
I would like make client works as browser(When browser use web server certificate).
I mean browser don't know webserver's certificate before connection, it can obtain it from web server.
My server's web.config:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" />
<services>
<service behaviorConfiguration="security" name="WebApplicationExchange.UKService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="security" contract="WebApplicationExchange.IUKService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="https://localhost/UKService/UKService.svc" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="security">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ServiceAuthorization.PasswordValidator,ServiceAuthorization" />
<windowsAuthentication allowAnonymousLogons="false" />
</serviceCredentials>
<serviceAuthorization principalPermissionMode="Custom">
<authorizationPolicies>
<add policyType="ServiceAuthorization.AuthorizationPolicy,ServiceAuthorization" />
</authorizationPolicies>
</serviceAuthorization>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="security">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="Basic" />
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
It works fine with web browsers.
But client show error:
Could not establish trust connection for secure channel SSL / TLS with authority "localhost: 56389".
Client code:
System.ServiceModel.EndpointAddress eaSecurity = new System.ServiceModel.EndpointAddress("https://localhost:56389/UKService.svc");
var binding = new System.ServiceModel.BasicHttpBinding();
binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportWithMessageCredential;
binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.None;
binding.Security.Message.ClientCredentialType = System.ServiceModel.BasicHttpMessageCredentialType.UserName;
var securityFactory = new System.ServiceModel.ChannelFactory<ServiceReference1.IUKService>(binding, eaSecurity);
securityFactory.Credentials.UserName.UserName = "test";
securityFactory.Credentials.UserName.Password = "test";
myService = securityFactory.CreateChannel();
Any ideas how to solve this?
UPDATE:
I look deeper in error stack and find following:
System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the results of authentication.
I tryed this code:
ClientCredentials cc = securityFactory.Endpoint.Behaviors.Find<ClientCredentials>();
cc.UserName.UserName = "test";
cc.UserName.Password = "test";
cc.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
But it doesn't help.
I solve it this way:
System.Net.ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertValidateCallback);
public static bool RemoteCertValidateCallback(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
return true;
}
The problem is that your certificate is not trusted by the client. This has nothing to do with client certificates or downloading the certificate from the browser.
In order for the server certificate to be accepted by te client, you need to either:
Buy a certificate from a trusted certificate authority
Add the certificate (or its root) to the client machine's certificate store or
Disable certificate validation.

Categories

Resources