WCF Service running on localhost (debug) but failing at deployment - wcf

I have a WCF Service that works when i run it at localhost, using the WCF Test Client I can invoke it and get a result. I can also see it when I actually host it on the live server as it generates the methods on the test client and I can see the wsdl page when opened in Chrome.
But (because it always has a but) when I invoke it with WCF Test Client I get this error:
Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc) 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)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at IRp3Services.CreateTransaction(NewTransaction model) at Rp3ServicesClient.CreateTransaction(NewTransaction model)
I cant seem to understand why, I have tested it locally and works perfectly, here is the web config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="ConsultasSoap" />
<binding name="TransaccionesSoap" />
<binding name="SeguridadSoap" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://address/Rp3.Web.Credishop.Afiliados/consultas.asmx"
binding="basicHttpBinding" bindingConfiguration="ConsultasSoap"
contract="RP3Consultas.ConsultasSoap" name="ConsultasSoap" />
<endpoint address="http://address/Rp3.Web.Credishop.Afiliados/transacciones.asmx"
binding="basicHttpBinding" bindingConfiguration="TransaccionesSoap"
contract="RP3Transacciones.TransaccionesSoap" name="TransaccionesSoap" />
<endpoint address="http://address/Rp3.Web.Credishop.Afiliados/seguridad.asmx"
binding="basicHttpBinding" bindingConfiguration="SeguridadSoap"
contract="RP3Seguridad.SeguridadSoap" name="SeguridadSoap" />
</client>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpBinding" scheme="http" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<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="true"/>
</system.webServer>
</configuration>
I am really at a loss here, I would love any input on what I am doing wrong here.

Related

{error: (403) Forbidden."} WCF basicHttpBinding with Transport and Certificate Credential

I get the error "{"The remote server returned an error: (403) Forbidden."} The HTTP request was forbidden with client authentication scheme 'Anonymous'." when using basicHttpBinding with Transport security and certificate credential. My service is in amazon ec2 instance and my client app remotely connect to it over the internet. I am able to connect to the wcf service if my Transport credential is set to "None" in both the web.config of the service and app.config of the client. My service certificate is like "www.example.com" is installed on amazon ec2 "local machine store" and "Personal Folder". My client app certificate is just a self-signed certificate which I installed to its "local machine and Personal Folder" and also to the "Trusted People store" in the amazon ec2 instance where my wcf service is. I have also setup "https" to my IIS site bindings and I can reach the site through like "https://www.example.com"
Below is the web.config, app.config, and the code I have on the client app.
Service Web.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="Off"/>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBinding_Config" >
<security mode="Transport">
<transport clientCredentialType="Certificate"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="MyProject.MyService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpBinding_Config"
contract="MyService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="PeerOrChainTrust" trustedStoreLocation="LocalMachine"/>
</clientCertificate>
<serviceCertificate findValue="www.example.com" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Client app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBinding_Config" >
<security mode="Transport">
<transport clientCredentialType="Certificate"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://www.example.com/sub/Service1.svc"
binding="basicHttpBinding" bindingConfiguration="basicHttpBinding_Config"
contract="ServiceReference1.MyService" name="BasicHttpBinding_MyService" />
</client>
<behaviors>
<endpointBehaviors>
<behavior>
<clientCredentials>
<clientCertificate findValue="clientKey"
storeLocation="LocalMachine"
storeName="My"
x509FindType="FindBySubjectName" />
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Client App Console Code:
static void Main(string[] args)
{
System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
ServiceReference1.MyServiceClient client = new ServiceReference1.MyServiceClient();
string[] a = client.GetMethods(ref mh);
foreach (string s in a)
{
Console.WriteLine(s);
}
Console.ReadKey();
}
The Diagnostic Tracing returns below:
<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
<System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
<EventID>131077</EventID>
<Type>3</Type>
<SubType Name="Critical">0</SubType>
<Level>1</Level>
<TimeCreated SystemTime="2018-11-16T21:50:58.8220239Z" />
<Source Name="System.ServiceModel" />
<Correlation ActivityID="{00000000-0000-0000-0000-000000000000}" />
<Execution ProcessName="ConsoleApplication1" ProcessID="22220" ThreadID="1" />
<Channel />
<Computer>DESKTOP-RPNI11M</Computer>
</System>
<ApplicationData>
<TraceData>
<DataItem>
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical">
<TraceIdentifier>UnhandledException</TraceIdentifier>
<Description>Unhandled exception</Description>
<AppDomain>ConsoleApplication1.exe</AppDomain>
<Exception>
<ExceptionType>System.ServiceModel.Security.MessageSecurityException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The HTTP request was forbidden with client authentication scheme 'Anonymous'.</Message>
<StackTrace>
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory`1 factory)
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.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)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at ConsoleApplication1.ServiceReference1.IOD_V416.GetMethods(GetMethodsRequest request)
at ConsoleApplication1.ServiceReference1.OD_V416Client.ConsoleApplication1.ServiceReference1.IOD_V416.GetMethods(GetMethodsRequest request) in D:\Workfolder\Projects2\MyProject\WCF_App\MyService - Copy (3)\ConsoleApplication1\Service References\ServiceReference1\Reference.cs:line 72017
at ConsoleApplication1.ServiceReference1.OD_V416Client.GetMethods(MultiSpeakMsgHeader& MultiSpeakMsgHeader) in D:\Workfolder\Projects2\MyProject\WCF_App\MyService - Copy (3)\ConsoleApplication1\Service References\ServiceReference1\Reference.cs:line 72023
at ConsoleApplication1.Program.Main(String[] args) in D:\Workfolder\Projects2\MyProject\WCF_App\MyService - Copy (3)\ConsoleApplication1\Program.cs:line 43
</StackTrace>
<ExceptionString>System.ServiceModel.Security.MessageSecurityException: The HTTP request was forbidden with client authentication scheme 'Anonymous'. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory`1 factory)
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.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)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at ConsoleApplication1.ServiceReference1.IOD_V416.GetMethods(GetMethodsRequest request)
at ConsoleApplication1.ServiceReference1.OD_V416Client.ConsoleApplication1.ServiceReference1.IOD_V416.GetMethods(GetMethodsRequest request) in D:\Workfolder\Projects2\MyProject\WCF_App\MyService - Copy (3)\ConsoleApplication1\Service References\ServiceReference1\Reference.cs:line 72017
at ConsoleApplication1.ServiceReference1.OD_V416Client.GetMethods(MultiSpeakMsgHeader& MultiSpeakMsgHeader) in D:\Workfolder\Projects2\MyProject\WCF_App\MyService - Copy (3)\ConsoleApplication1\Service References\ServiceReference1\Reference.cs:line 72023
at ConsoleApplication1.Program.Main(String[] args) in D:\Workfolder\Projects2\MyProject\WCF_App\MyService - Copy (3)\ConsoleApplication1\Program.cs:line 43</ExceptionString>
<InnerException>
<ExceptionType>System.Net.WebException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The remote server returned an error: (403) Forbidden.</Message>
<StackTrace>
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
</StackTrace>
<ExceptionString>System.Net.WebException: The remote server returned an error: (403) Forbidden.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)</ExceptionString>
</InnerException>
</Exception>
</TraceRecord>
</DataItem>
</TraceData>
</ApplicationData>
</E2ETraceEvent>
I did look to other similar issues but none has solve it yet, I'm continuously searching for the right solutions, I appreciate any help or advice the community provides.
EDIT:
Probably better to use a sha2 cert:
makecert -len 2048 -r -a sha256 -sv private.pvk -n CN=yoursubjectname cert.cer
pvk2pfx -spc cert.cer -pvk private.pvk -pfx out.pfx
Install the private cert(.pfx) on the host, set in IIS app, and install the public cert on the client(.cer), you will have to install in both personal and trusted people stores.
EDIT: I think you also need to give your behavior a name in the host and client config and assign that behavior to your endpoints.
Host:
<behavior name="serviceBahavior">
<service name="MyProject.MyService" behaviorConfiguration="serviceBahavior">
Client:
<behavior name="clientBahavior">
<endpoint address="https://www.example.com/sub/Service1.svc"
binding="basicHttpBinding" bindingConfiguration="basicHttpBinding_Config"
contract="ServiceReference1.MyService" name="BasicHttpBinding_MyService" behaviorConfiguration="clientBahavior" />
I think since you are using <security mode="Transport"> you will need to make your mex as HTTPS:
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
Also set in your behavior the serviceMetadata
from:
<serviceMetadata httpGetEnabled="true"/>
to <serviceMetadata httpsGetEnabled="true"/>
Also, make sure your transport in the client config matches the host config:
<transport clientCredentialType="Certificate"/>
I found the following solution that works for this error I encountered.
First, I created a certificate as follows:
makecert -n "CN=MyRootSigningKey" -r -sv MyRootSigningKey.pvk MyRootSigningKey.cer
Second, I treat this as my root key and install it in my AWS service under the certificate store "Trusted Root Certification Authorities" using mmc.
Third, I created a self-signed cert using the root key "MyRootSigningKey" as follows:
makecert -sk MySignedKeyName -iv MyRootSigningKey.pvk -n "CN=MySignedKey" -ic MyRootSigningKey.cer -sr localmachine -ss my -sky exchange -pe
Last, I reference the self signed cert "MySignedKey" in my client app config like below:
<client>
<endpoint address="https://www.example.com/sub/Service1.svc" behaviorConfiguration="clientBehavior"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_MyService"
contract="ServiceReference1.MyService" />
</client>
<behaviors>
<endpointBehaviors>
<behavior name="clientBehavior">
<clientCredentials>
<clientCertificate findValue="MySignedKey"
storeLocation="LocalMachine"
storeName="My"
x509FindType="FindBySubjectName" />
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>

MessageSecurityException with ACS issued token and WIF

I'm using ACS/Service Identities as a temporary STS while I get things into place. Unfortunately, while I appear to be able to get a SAML 1.1 token fine from ACS, the second I try to pass it into my WCF service things go crazy. As far as I can tell, the token isn't expired (it's being used promptly), I'm not sure how it could be invalid, and nothing I've done with logging has displayed to me any detail on what exactly could be wrong. I'm tempted to assign blame to the binding, because I've never done a formal WCF/WIF binding before. Can anyone see anything wrong with the client/server bindings I'm using (the client was generated via service reference), or suggest an alterative avenue of investigation?
BTW, both the server and client are running on the same development machine.
Web.config:
<configuration>
<configSections>
<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="ida:FederationMetadataLocation" value="--omitted--" />
<add key="ida:ProviderSelection" value="productionSTS" />
</appSettings>
<location path="FederationMetadata">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceCredentials useIdentityConfiguration="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add scheme="https" binding="ws2007FederationHttpBinding" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<bindings>
<ws2007FederationHttpBinding>
<binding name="">
<security mode="TransportWithMessageCredential">
<message issuedKeyType="BearerKey" issuedTokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"/>
</security>
</binding>
</ws2007FederationHttpBinding>
</bindings>
</system.serviceModel>
<system.webServer>
<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="true" />
</system.webServer>
<system.identityModel>
<identityConfiguration>
<audienceUris>
<add value="https://localhost:44300/Service1.svc" />
</audienceUris>
<issuerNameRegistry>
<trustedIssuers>
<add name="--omitted--" thumbprint="--omitted--"/>
</trustedIssuers>
</issuerNameRegistry>
<certificateValidation certificateValidationMode="None"/>
</identityConfiguration>
</system.identityModel>
</configuration>
App.config:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" />
</basicHttpBinding>
<ws2007FederationHttpBinding>
<binding name="WS2007FederationHttpBinding_IService1">
<security mode="TransportWithMessageCredential">
<message issuedKeyType="BearerKey" issuedTokenType="">
<tokenRequestParameters>
<trust:SecondaryParameters xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">
<trust:TokenType xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1</trust:TokenType>
<trust:KeyType xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer</trust:KeyType>
<trust:CanonicalizationAlgorithm xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/10/xml-exc-c14n#</trust:CanonicalizationAlgorithm>
<trust:EncryptionAlgorithm xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/04/xmlenc#aes256-cbc</trust:EncryptionAlgorithm>
</trust:SecondaryParameters>
</tokenRequestParameters>
</message>
</security>
</binding>
</ws2007FederationHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:51853/Service1.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
name="BasicHttpBinding_IService1" />
<endpoint address="https://localhost:44300/Service1.svc" binding="ws2007FederationHttpBinding"
bindingConfiguration="WS2007FederationHttpBinding_IService1"
contract="ServiceReference1.IService1" name="WS2007FederationHttpBinding_IService1" />
</client>
</system.serviceModel>
Client code:
static void Main(string[] args)
{
var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress("--Azure ACS URL omitted--"));
factory.TrustVersion = TrustVersion.WSTrust13;
factory.Credentials.UserName.UserName = "--omitted--";
factory.Credentials.UserName.Password = "--omitted--";
var rst = new RequestSecurityToken
{
RequestType = RequestTypes.Issue,
KeyType = KeyTypes.Bearer,
AppliesTo = new EndpointReference("https://localhost:44300/Service1.svc")
};
SecurityToken token = factory.CreateChannel().Issue(rst);
var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
binding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;
binding.Security.Message.EstablishSecurityContext = false;
var factory2 = new ChannelFactory<IService1>(binding, new EndpointAddress("https://localhost:44300/Service1.svc"));
factory2.Credentials.SupportInteractive = false;
factory2.Credentials.UseIdentityConfiguration = true;
var proxy = factory2.CreateChannelWithIssuedToken(token);
var info = proxy.GetData("testing"); // Exception thrown here
}
Exception:
System.ServiceModel.Security.MessageSecurityException was unhandled
HResult=-2146233087
Message=An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.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)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at TestWCFClient.ServiceReference1.IService1.GetData(String value)
at TestWCFClient.Program.Main(String[] args) in c:\Users\nicole\Documents\Visual Studio 2012\Projects\TestWCFClient\Program.cs:line 43
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.ServiceModel.FaultException
HResult=-2146233087
Message=The message could not be processed. This is most likely because the action 'http://tempuri.org/IService1/GetData' is incorrect or because the message contains an invalid or expired security context token or because there is a mismatch between bindings. The security context token would be invalid if the service aborted the channel due to inactivity. To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding.
InnerException:
ETA:
In addition, I've tried: switching to SAML 2.0, switching to JWT with the preview JWT token handler, changing the receive timeout, switching the host machine time to UTC, syncing the host with the Windows Time Service explicitly, and waiting for five minutes after the token is issued before using it.
The MessageSecurityException was right: it's a binding error.
I was mixing a couple of code samples together and got bitten by the mismatch. EstablishSecurityContext is not just window dressing, it is a real part of the binding, and the values must match between service and client.
My application code reads:
var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
binding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;
binding.Security.Message.EstablishSecurityContext = false; // this line is the problem
The service binding is:
<bindings>
<ws2007FederationHttpBinding>
<binding name="">
<security mode="TransportWithMessageCredential">
<message issuedKeyType="BearerKey" issuedTokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"/> <!-- this line does not match -->
</security>
</binding>
</ws2007FederationHttpBinding>
</bindings>
The service binding should be:
<bindings>
<ws2007FederationHttpBinding>
<binding name="">
<security mode="TransportWithMessageCredential">
<message issuedKeyType="BearerKey" establishSecurityContext="false"/>
</security>
</binding>
</ws2007FederationHttpBinding>
</bindings>
And presto, it works.

Windows Service Bus 1.0, Appfabric, Netmessagingbinding failuring

I seem to run into the same problem over and over again when I am trying to host a WCF service in Windows Server AppFabric that uses netmessagingbinding to receive messages from Windows Service Bus 1.0 queues. AppFabric aborts the service, so if I press F5 on service?wsdl then I sometimes get failures, sometimes I get a nice WSDL generated. Where is my mistake? It is rather impossible to find an example that uses AppFabric, netmessagingbinding and Windows Service Bus (not Azure), so I haven't been able to finde my mistake...
[ServiceContract]
public interface ISBMessageService
{
[OperationContract(IsOneWay = true, Action = "DoSomething")]
[ReceiveContextEnabled(ManualControl = true)]
void DoSomething(string something);
}
[ServiceBehavior]
public class SBMessageService : ISBMessageService
{
[OperationBehavior]
public void DoSomething(string something)
{
Trace.WriteLine(String.Format("You sent {0}", something));
// Get the BrokeredMessageProperty from the current OperationContext
var incomingProperties = OperationContext.Current.IncomingMessageProperties;
var property = incomingProperties[BrokeredMessageProperty.Name] as BrokeredMessageProperty;
ReceiveContext receiveContext;
if (ReceiveContext.TryGet(incomingProperties, out receiveContext))
{
receiveContext.Complete(TimeSpan.FromSeconds(10.0d));
}
else
{
throw new InvalidOperationException("...");
}
}
}
<?xml version="1.0"?>
<configuration>
<appSettings>
<!-- Service Bus specific app setings for messaging connections -->
<add key="Microsoft.ServiceBus.ConnectionString"
value="Endpoint=sb://LRNcomp/LRNnamespace"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
</system.web>
<system.serviceModel>
<!-- These <extensions> will not be needed once our sdk is installed-->
<extensions>
<bindingElementExtensions>
<add name="netMessagingTransport" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingTransportExtensionElement, Microsoft.ServiceBus, Version=1.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</bindingElementExtensions>
<bindingExtensions>
<add name="netMessagingBinding" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingBindingCollectionElement, Microsoft.ServiceBus, Version=1.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</bindingExtensions>
<behaviorExtensions>
<add name="transportClientEndpointBehavior" type="Microsoft.ServiceBus.Configuration.TransportClientEndpointBehaviorElement, Microsoft.ServiceBus, Version=1.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</behaviorExtensions>
</extensions>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="True" httpHelpPageEnabled="True"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="securityBehavior">
<transportClientEndpointBehavior>
<tokenProvider>
<sharedSecret issuerName="owner" issuerSecret="somthing"/>
</tokenProvider>
</transportClientEndpointBehavior>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<netMessagingBinding>
<binding name="messagingBinding" closeTimeout="00:03:00" openTimeout="00:03:00" receiveTimeout="00:03:00" sendTimeout="00:03:00" sessionIdleTimeout="00:01:00" prefetchCount="-1">
<transportSettings batchFlushInterval="00:00:01"/>
</binding>
</netMessagingBinding>
</bindings>
<services>
<service name="SBExamples.SBMessageService">
<endpoint name="Service1" address="sb://LRNcomp:9354/LRNnamespace/test/myqueue2" binding="netMessagingBinding" bindingConfiguration="messagingBinding" contract="SBExamples.ISBMessageService" behaviorConfiguration="securityBehavior"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<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="true"/>
</system.webServer>
</configuration>
An error in the WCF contract generated many strange exceptions, like my transport channel was aborted. Proper sharing of contract between sender and receiver did the trick.

An error occurred when verifying security for the message when client try to consume WCF

I am trying to use wcf service authentication without SSL by using this link :
http://webservices20.blogspot.in/2008/11/introducing-wcf-clearusernamebinding.html
Every thing goes fine till i publish the service.but when i try to consume service with asp.net webClient then it throw
An error occurred when verifying security for the message exception
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
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)
my web config file is :
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<extensions>
<bindingExtensions>
<add name="clearUsernameBinding" type="WebServices20.BindingExtenions.ClearUsernameCollectionElement, ClearUsernameBinding" />
</bindingExtensions>
</extensions>
<bindings>
<clearUsernameBinding>
<binding name="myClearUsernameBinding" messageVersion="Soap12">
</binding>
</clearUsernameBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="SampleServiceBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="QService.MyUserNameValidator,QService" />
</serviceCredentials>
</behavior>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="QService.Service1" behaviorConfiguration="SampleServiceBehaviour">
<endpoint binding="clearUsernameBinding" bindingConfiguration="myClearUsernameBinding" contract="QService.IService1" />
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
and my client code is :
ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient();
obj.ClientCredentials.UserName.UserName = "user";
obj.ClientCredentials.UserName.Password = "pass";
Response.Write(obj.GetData(45));
thanks in advance

invalid mscorlib exception in custom security attribute c'tor

I'm trying to implement my custom security attribute. It's very simple for now
[Serializable]
[ComVisible(true)]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
public class SecPermissionAttribute : CodeAccessSecurityAttribute
{
public SecPermissionAttribute(SecurityAction action) : base(action) { }
public override System.Security.IPermission CreatePermission()
{
IPermission perm = new PrincipalPermission(PermissionState.Unrestricted);
return perm;
}
}
For some reason I've got an exception in the attribute c'tor
System.IO.FileLoadException occurred
Message=The given assembly name or codebase, 'C:\WINDOWS\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll', was invalid.
Source=WcfRoleProviderTestService
StackTrace:
at SecLib.SecPermissionAttribute..ctor(SecurityAction action)
at WcfRoleProviderTestService.Service1.GetData(Int32 value) in D:\TestProjects\WcfRoleProviderTestService\WcfRoleProviderTestService\Service1.svc.cs:line 19
InnerException:
The dll is signed. It seems to me like a security issue but I'm not sure. By the way I tried to use PrincipalPermissionAttribute and it works fine.
Forgot to say, I'm using VS 2010, FW 4.0, the attribute is concumed in the WCF service
I'll be very glad to get some help.
My service configuration is the following
<system.web>
<compilation debug="true" defaultLanguage="c#" targetFramework="4.0" />
<roleManager enabled="true" cacheRolesInCookie="true" cookieName=".ASPROLES"
defaultProvider="MyRoleProvider">
<providers>
<clear />
<add connectionStringName="Service1" applicationName="InfraTest"
writeExceptionsToEventLog="false" name="MyRoleProvider" type="SecLib.MyRoleProvider, SecLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=798c04e15cff851a" />
</providers>
</roleManager>
</system.web>
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBindingConfiguration" closeTimeout="00:01:00"
sendTimeout="00:10:00" maxBufferSize="524288" maxReceivedMessageSize="524288">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="WcfRoleProviderTestService.Service1"
behaviorConfiguration="BasicHttpServiceBehavior" >
<endpoint name="BasicHttpEndpoint"
contract="WcfRoleProviderTestService.IService1"
address="WcfAuthenticationTest"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBindingConfiguration" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost/WcfRoleProviderTestService/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="BasicHttpServiceBehavior">
<serviceAuthorization principalPermissionMode="UseAspNetRoles"
roleProviderName="MyRoleProvider" impersonateCallerForAllOperations="true" />
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
I've got the error both on Windows XP, IIS v5.1 and on Windows Server 2008 R2 IISV7.5 only if the WCF service is configured to use Windows Authentication (see the configuration above). On more interesting fact is that the error occured only if the attribute is used with the System.Security.Permissions.SecurityAction.Demand security action.
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[SecPermission(System.Security.Permissions.SecurityAction.Demand)]
public string GetData(int value)
{
string userName = ServiceSecurityContext.Current.WindowsIdentity.Name;
return string.Format("You entered: {0}, User {1}", value, userName);
}
Other options work fine.
Thanks.
With a help of one of my colleagues, the problem has been soleved. I'm not sure what the exact reason of the exception was but it seems to be a compilation issue. When I changed the project type from web application to web site wich is compiled at run time according it's pool definition (64 or 32 bit) it started to work fine.