Securing backend WCF service with WIF using ADFS2 as IP - wcf

I’m having an issue using ADFS2 to secure a back-end WCF service that is being called from Passively Federated Website. I have the passive federation working on the website, but the back-end service is giving me problems.
The pieces of the puzzle.
Silverlight Client that is being served from Passively Federated Website.
The Silverlight calls a WCF service (App Service), hosted on the passively Federated Website.
I have SaveBootstrapToken set to true in the config.
From the App Service, I want to call a back-end WCF service using BootstrapToken with the ActAs scenarion.
Federated Website and Back-end WCF service are setup as separate RPs in the ADFS2, token encryption is turned on. Both are allowed to delegate.
Back-end Service configuration:
I have WIF incorporated into the pipeline using behavior extension.
<ws2007FederationHttpBinding>
<binding name="WS2007FederationHttpBinding_IQuoteService">
<security mode="TransportWithMessageCredential">
<message establishSecurityContext="false">
<issuer address="https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256">
</issuer>
<issuerMetadata address="https://myADFSserver/adfs/services/trust/mex">
</issuerMetadata>
</message>
</security>
</binding>
</ws2007FederationHttpBinding>
<behaviors>
<serviceBehaviors>
<behavior name="">
<federatedServiceHostConfiguration name="Service.QuoteService" />
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceCredentials>
<serviceCertificate findValue="000000000000000000000000000000" storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="Service.QuoteService">
<endpoint address="" binding="ws2007FederationHttpBinding" contract="Service.IQuoteService" bindingConfiguration="WS2007FederationHttpBinding_IQuoteService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
Client Configuration
When add the service using Add Service Reference tooling, the following config on the client gets created:
<customBinding>
<binding name="https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256">
<security defaultAlgorithmSuite="Default" authenticationMode="IssuedTokenOverTransport"
requireDerivedKeys="false" securityHeaderLayout="Strict" includeTimestamp="true"
keyEntropyMode="CombinedEntropy" messageSecurityVersion="WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10">
<issuedTokenParameters keySize="256" keyType="SymmetricKey" tokenType="">
<additionalRequestParameters>
<trust:SecondaryParameters xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">
<trust:KeyType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey</trust:KeyType>
<trust:KeySize>256</trust:KeySize>
<trust:KeyWrapAlgorithm>http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p</trust:KeyWrapAlgorithm>
<trust:EncryptWith>http://www.w3.org/2001/04/xmlenc#aes256-cbc</trust:EncryptWith>
<trust:SignatureAlgorithm>http://www.w3.org/2000/09/xmldsig#hmac-sha1</trust:SignatureAlgorithm>
<trust:CanonicalizationAlgorithm>http://www.w3.org/2001/10/xml-exc-c14n#</trust:CanonicalizationAlgorithm>
<trust:EncryptionAlgorithm>http://www.w3.org/2001/04/xmlenc#aes256-cbc</trust:EncryptionAlgorithm>
</trust:SecondaryParameters>
</additionalRequestParameters>
</issuedTokenParameters>
<localClientSettings cacheCookies="true" detectReplays="false"
replayCacheSize="900000" maxClockSkew="00:05:00" maxCookieCachingTime="Infinite"
replayWindow="00:05:00" sessionKeyRenewalInterval="10:00:00"
sessionKeyRolloverInterval="00:05:00" reconnectTransportOnFailure="true"
timestampValidityDuration="00:05:00" cookieRenewalThresholdPercentage="60" />
<localServiceSettings detectReplays="false" issuedCookieLifetime="10:00:00"
maxStatefulNegotiations="128" replayCacheSize="900000" maxClockSkew="00:05:00"
negotiationTimeout="00:01:00" replayWindow="00:05:00" inactivityTimeout="00:02:00"
sessionKeyRenewalInterval="15:00:00" sessionKeyRolloverInterval="00:05:00"
reconnectTransportOnFailure="true" maxPendingSessions="128"
maxCachedCookies="1000" timestampValidityDuration="00:05:00" />
<secureConversationBootstrap />
</security>
<textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
messageVersion="Default" writeEncoding="utf-8">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</textMessageEncoding>
<httpsTransport manualAddressing="false" maxBufferPoolSize="524288"
maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
bypassProxyOnLocal="false" decompressionEnabled="true" hostNameComparisonMode="StrongWildcard"
keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
useDefaultWebProxy="true" requireClientCertificate="false" />
</binding>
</customBinding>
<ws2007FederationHttpBinding>
<binding name="WS2007FederationHttpBinding_IQuoteService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
textEncoding="utf-8" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<message algorithmSuite="Default" issuedKeyType="SymmetricKey"
negotiateServiceCredential="true">
<issuer address="https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256"
binding="customBinding" bindingConfiguration="https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256" />
<issuerMetadata address="https://myADFSserver/adfs/services/trust/mex" />
<tokenRequestParameters>
<trust:SecondaryParameters xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">
<trust:KeyType xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey</trust:KeyType>
<trust:KeySize xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">256</trust:KeySize>
<trust:Claims Dialect="http://schemas.xmlsoap.org/ws/2005/05/identity"
xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">
<wsid:ClaimType Uri="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
Optional="true" xmlns:wsid="http://schemas.xmlsoap.org/ws/2005/05/identity" />
<wsid:ClaimType Uri="http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
Optional="true" xmlns:wsid="http://schemas.xmlsoap.org/ws/2005/05/identity" />
</trust:Claims>
<trust:KeyWrapAlgorithm xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p</trust:KeyWrapAlgorithm>
<trust:EncryptWith xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/04/xmlenc#aes256-cbc</trust:EncryptWith>
<trust:SignWith xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2000/09/xmldsig#hmac-sha1</trust:SignWith>
<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>
<client>
<endpoint address="http://myServiceHost/Service/QuoteService.svc"
binding="ws2007FederationHttpBinding" bindingConfiguration="WS2007FederationHttpBinding_IQuoteService"
contract="QuoteService.IQuoteService" name="WS2007FederationHttpBinding_IQuoteService">
<identity>
<certificate encodedValue="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
</identity>
</endpoint>
</client>
Here's the Service Client Code:
List<Quote> quoteList = new List<Quote>();
ClaimsPrincipal myClaimsPrincipal = System.Web.HttpContext.Current.User as ClaimsPrincipal;
SecurityToken bootstrapToken = myClaimsPrincipal.Identities[0].BootstrapToken;
if (bootstrapToken == null)
{
throw new Exception("bootstrap tokein is null. Logout and try again.");
}
ChannelFactory<IQuoteServiceChannel> factory = new ChannelFactory<IQuoteServiceChannel>("WS2007FederationHttpBinding_IQuoteService");
factory.Credentials.SupportInteractive = false;
factory.Credentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "0000000000000000000000000000");
factory.ConfigureChannelFactory();
IQuoteServiceChannel channel;
//Create the channel with the bootstrap token
channel = factory.CreateChannelActingAs(bootstrapToken);
try
{
quoteList = channel.GetQuotes(quoteUser);
channel.Close();
}
catch (SecurityAccessDeniedException sadex)
{
channel.Abort();
throw;
}
catch (CommunicationException exception)
{
channel.Abort();
throw;
}
catch (TimeoutException timeoutEx)
{
channel.Abort();
throw;
}
catch (Exception ex)
{
channel.Abort();
throw;
}
return quoteList;
This is the exception I get:
System.ServiceModel.Security.SecurityNegotiationException was unhandled by user code
Message=SOAP security negotiation with 'https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256' for target 'https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256' failed. See inner exception for more details.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Security.IssuanceTokenProviderBase`1.DoNegotiation(TimeSpan timeout)
at System.ServiceModel.Security.IssuanceTokenProviderBase`1.GetTokenCore(TimeSpan timeout)
at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan timeout)
at Microsoft.IdentityModel.Protocols.WSTrust.FederatedSecurityTokenProvider.GetTokenCore(TimeSpan timeout)
at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan timeout)
at System.ServiceModel.Security.SecurityProtocol.TryGetSupportingTokens(SecurityProtocolFactory factory, EndpointAddress target, Uri via, Message message, TimeSpan timeout, Boolean isBlockingCall, IList`1& supportingTokens)
at System.ServiceModel.Security.SymmetricSecurityProtocol.TryGetTokenSynchronouslyForOutgoingSecurity(Message message, SecurityProtocolCorrelationState correlationState, Boolean isBlockingCall, TimeSpan timeout, SecurityToken& token, SecurityTokenParameters& tokenParameters, SecurityToken& prerequisiteWrappingToken, IList`1& supportingTokens, SecurityProtocolCorrelationState& newCorrelationState)
at System.ServiceModel.Security.SymmetricSecurityProtocol.SecureOutgoingMessageCore(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
at System.ServiceModel.Security.MessageSecurityProtocol.SecureOutgoingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation operation, EndpointAddress target, Uri via, SecurityToken currentToken, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetTokenCore(TimeSpan timeout)
at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
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 OMG.Admin.DemoApp.Business.QuoteService.IQuoteService.GetQuotes(User quoteUser)
at OMG.Admin.DemoApp.Business.QuoteServiceClient.GetQuotes(User quoteUser) in C:\OMG_TFS01\OMG.Admin\OMG.Admin.DemoApp\OMG.Admin.DemoApp.Business\QuoteServiceClient.cs:line 131
at OMG.Admin.DemoApp.Business.QuoteBO.GetQuoteList() in C:\OMG_TFS01\OMG.Admin\OMG.Admin.DemoApp\OMG.Admin.DemoApp.Business\QuoteBO.cs:line 26
at OMG.Admin.DemoApp.Web.Services.DemoAppService.GetQuotes() in C:\OMG_TFS01\OMG.Admin\OMG.Admin.DemoApp\OMG.Admin.DemoApp.Web\Services\DemoAppService.svc.cs:line 27
at SyncInvokeGetQuotes(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
InnerException: System.InvalidOperationException
Message=The address of the security token issuer is not specified. An explicit issuer address must be specified in the binding for target 'https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256' or the local issuer address must be configured in the credentials.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.ClientCredentialsSecurityTokenManager.CreateIssuedSecurityTokenProvider(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement)
at System.ServiceModel.ClientCredentialsSecurityTokenManager.CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement, Boolean disableInfoCard)
at Microsoft.IdentityModel.Protocols.WSTrust.FederatedClientCredentialsSecurityTokenManager.CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement)
at System.ServiceModel.Security.SecurityProtocol.AddSupportingTokenProviders(SupportingTokenParameters supportingTokenParameters, Boolean isOptional, IList`1 providerSpecList)
at System.ServiceModel.Security.SecurityProtocol.OnOpen(TimeSpan timeout)
at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.ClientSecurityChannel`1.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
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 System.ServiceModel.ICommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Security.IssuanceTokenProviderBase`1.DoNegotiation(TimeSpan timeout)
InnerException:
I'm sure I'm missing something in the configuration and/or code can someone help me out?

I got this scenario working, here’s the solution for anyone interested.
Followed Dominick Baier’s post for ideas / code: http://leastprivilege.com/2010/10/14/wif-adfs-2-and-wcfpart-5-service-client-more-flexibility-with-wstrustchannelfactory/
I changed the back-end WCF service config to this:
<microsoft.identityModel>
<service>
<audienceUris>
<add value="https://localhost/Service/QuoteService.svc" />
<add value="https://localhost/Service/" />
</audienceUris>
<serviceCertificate>
<certificateReference x509FindType="FindByThumbprint" findValue="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
</serviceCertificate>
<issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<trustedIssuers>
<add thumbprint="000000000000000000000000000000000000" name="http://myADFSserver/adfs/services/trust" />
</trustedIssuers>
</issuerNameRegistry>
<certificateValidation certificateValidationMode="None" />
</service>
</microsoft.identityModel>
<system.serviceModel>
<services>
<service name="Service.QuoteService">
<endpoint address=""
binding="ws2007FederationHttpBinding"
contract="Service.IQuoteService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<ws2007FederationHttpBinding>
<binding>
<security mode="TransportWithMessageCredential">
<message establishSecurityContext="false">
<issuerMetadata address="https://myADFSserver/adfs/services/trust/mex" />
</message>
</security>
</binding>
</ws2007FederationHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpsGetEnabled="true" />
<federatedServiceHostConfiguration />
</behavior>
</serviceBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="federatedServiceHostConfiguration"
type="Microsoft.IdentityModel.Configuration.ConfigureServiceHostBehaviorExtensionElement, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</behaviorExtensions>
</extensions>
</system.serviceModel>
I’m no longer using WCF config on the client, it’s all done in code.
Here’s the client code:
public QuoteServiceClient()
{
SecurityToken actAsToken = this.GetDelegatedTokenUsername();
var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
binding.Security.Message.EstablishSecurityContext = false;
ChannelFactory<IQuoteServiceChannel> factory =
new ChannelFactory<IQuoteServiceChannel>(binding, new EndpointAddress(svcEndpoint));
factory.ConfigureChannelFactory<IQuoteServiceChannel>();
factory.Credentials.SupportInteractive = false;
this.channel = factory.CreateChannelWithIssuedToken<IQuoteServiceChannel>(actAsToken);
}
private SecurityToken GetDelegatedTokenUsername()
{
var binding = new UserNameWSTrustBinding();
binding.SecurityMode = SecurityMode.TransportWithMessageCredential;
//UserNameMixed is this endpoint "/adfs/services/trust/13/usernamemixed"
WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(binding, new EndpointAddress(UserNameMixed));
trustChannelFactory.TrustVersion = System.ServiceModel.Security.TrustVersion.WSTrust13;
trustChannelFactory.Credentials.SupportInteractive = false;
//Some User Account
//It's used to access the ADFS Server
//Act as is the actual Identity that Will be used.
//If you use one of windows bindings (ex. windowstransport), you wont need this.
//The AppPool identity will be used then.
trustChannelFactory.Credentials.UserName.UserName = #"domain\username";
trustChannelFactory.Credentials.UserName.Password = "password";
try
{
RequestSecurityToken rst = new RequestSecurityToken();
rst.RequestType = WSTrust13Constants.RequestTypes.Issue;
rst.AppliesTo = new EndpointAddress(ServiceAppliesTo);
//This part will give you identity of logged in user
rst.ActAs = new SecurityTokenElement(this.GetBootStrapToken());
var channel = trustChannelFactory.CreateChannel();
RequestSecurityTokenResponse rstr = null;
SecurityToken delegatedToken = channel.Issue(rst, out rstr);
return delegatedToken;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
try
{
if (trustChannelFactory.State == CommunicationState.Faulted)
{
trustChannelFactory.Abort();
}
else
{
trustChannelFactory.Close();
}
}
catch (Exception)
{ }
}
}
private SecurityToken GetBootStrapToken()
{
ClaimsPrincipal myClaimsPrincipal = System.Web.HttpContext.Current.User as ClaimsPrincipal;
SecurityToken bootstrapToken = myClaimsPrincipal.Identities[0].BootstrapToken;
if (bootstrapToken == null)
{
throw new Exception("bootstrap tokein is null. Logout and try again.");
}
return bootstrapToken;
}
That is all good and dandy, except you will not have proper claims on the back-end WCF service. Using this great article I was able to sort out the claim stuff in ADFS: http://technet.microsoft.com/en-us/library/adfs2-identity-delegation-step-by-step-guide.aspx . Scroll down to Enabling Identity Delegation and Fixing Claims Issuance Rules at CONTOSODC. I also removed claim encryption from Passively Federated Website.
After doing this I have same claims in the app service and the back-end WCF service.
I hope this helps someone in the same boat as I was.

Related

Receiving an error using URL Routing with built-in WCF Router Service

I wanted to create an extension less (file-less if possible) router endpoint via WCF Router Service that has customer user/password security policy. I am getting the following Fault Exception when attempting to route SOAP messages through it:
<s:Fault>
<faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:InternalServiceFault</faultcode>
<faultstring xml:lang="en-US">An unexpected failure occurred. Applications should not attempt to handle this error. For diagnostic purposes, this English message is associated with the failure: 'Shouldn't allocate SessionChannels if session-less and impersonating'.</faultstring>
<detail>
<ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<HelpLink i:nil="true"/>
<InnerException i:nil="true"/>
<Message>An unexpected failure occurred. Applications should not attempt to handle this error. For diagnostic purposes, this English message is associated with the failure: 'Shouldn't allocate SessionChannels if session-less and impersonating'.</Message>
<StackTrace>at System.Runtime.Fx.AssertAndThrow(String description)
at System.ServiceModel.Routing.RoutingChannelExtension.get_SessionChannels()
at System.ServiceModel.Routing.RoutingService.GetOrCreateClient[TContract](RoutingEndpointTrait endpointTrait, Boolean impersonating)
at System.ServiceModel.Routing.ProcessRequestAsyncResult`1.StartProcessing()
at System.ServiceModel.Routing.ProcessRequestAsyncResult`1..ctor(RoutingService service, Message message, AsyncCallback callback, Object state)
at System.ServiceModel.Routing.RoutingService.BeginProcessRequest[TContract](Message message, AsyncCallback callback, Object state)
at System.ServiceModel.Routing.RoutingService.System.ServiceModel.Routing.IRequestReplyRouter.BeginProcessRequest(Message message, AsyncCallback callback, Object state)
at AsyncInvokeBeginBeginProcessRequest(Object , Object[] , AsyncCallback , Object )
at System.ServiceModel.Dispatcher.AsyncMethodInvoker.InvokeBegin(Object instance, Object[] inputs, AsyncCallback callback, Object state)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace>
<Type>System.Runtime.Fx+InternalException</Type>
</ExceptionDetail>
</detail>
</s:Fault>
I did have to enabled AspNetCompability for the service host due to URL Routing.
Here are the steps that I followed:
I have set up a basic .net 4.0 web application with appropriate URL routing rules in RouteTable:
routes.Add(new ServiceRoute("routerservice", new CustomServiceHostFactory(), typeof(System.ServiceModel.Routing.RoutingService)));`
My CustomServiceHostFactory code:
public class CustomServiceHostFactory : ServiceHostFactory
{
protected override System.ServiceModel.ServiceHost CreateServiceHost(System.Type serviceType, System.Uri[] baseAddresses)
{
var host = base.CreateServiceHost(serviceType, baseAddresses);
var aspnet = host.Description.Behaviors.Find<AspNetCompatibilityRequirementsAttribute>();
if (aspnet == null)
{
aspnet = new AspNetCompatibilityRequirementsAttribute();
host.Description.Behaviors.Add(aspnet);
}
aspnet.RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed;
return host;
}
}
In web.config file I define the service endpoint and behavior:
<services>
<service name="System.ServiceModel.Routing.RoutingService" behaviorConfiguration="GatewayServiceBehavior">
<endpoint address="" binding="basicHttpBinding" contract="System.ServiceModel.Routing.IRequestReplyRouter" bindingConfiguration="GatewaySecureBinding" />
</service>
</services>
The binding and behavior configurations are straight forward with just a simple username/password validation requirement:
<binding name="GatewaySecureBinding" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxBufferSize="65536" maxReceivedMessageSize="65536"
textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"
messageEncoding="Mtom">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
<behavior name="GatewayServiceBehavior">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CustomLib.CustomUsernameValidator, CustomLib"/>
</serviceCredentials>
<routing filterTableName="RoutingTable1" routeOnHeadersOnly="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>

Object is not returned from the wcf web service

I have written a web service in wcf that returns a object. But When I call it from client code it does not return any object.
My class that object I want to return
[DataContract]
public class OrderData
{
[DataMember]
public List<ORDER_INFO> OrderInfoList { get; set; }
[DataMember]
public List<ORDER_PRODUCT_MAPPING> OrderProductMappingList { get; set; }
}
My Service Interface
[ServiceContract]
public interface ISyncService
{
[OperationContract]
OrderData InsertOrderData(decimal depotId);
}
Interface implementation class
public class SyncService : ISyncService
{
readonly InceptaDbContext _db = new InceptaDbContext();
public OrderData InsertOrderData(decimal depotId)
{
var orderData = new OrderData
{
OrderInfoList = new List<ORDER_INFO>(),
OrderProductMappingList = new List<ORDER_PRODUCT_MAPPING>()
};
var orderList = _db.ORDER_INFO
.Where(m => m.D_ID.Equals(depotId)&& m.STATUS.Equals("1"));
//.Where(m => m.STATUS.Equals("1"));
foreach (var orderInfo in orderList)
{
orderData.OrderInfoList.Add(orderInfo);
orderData.OrderProductMappingList.AddRange(
_db.ORDER_PRODUCT_MAPPING.Where(m => m.ORDER_ID.Equals
(orderInfo.ORDER_ID)));
}
foreach (var orderInfo in orderList)
{
orderInfo.STATUS = "2";
_db.Entry(orderInfo).State = EntityState.Modified;
}
_db.SaveChanges();
return orderData;
}
}
My server web Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<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>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<directoryBrowse enabled="true" />
</system.webServer>
<connectionStrings>
<add name="InceptaDbContext"
connectionString="metadata=res://*/DbContext.Model1.csdl|res://*/DbContext.Model1.ssdl|res://*/DbContext.Model1.msl;provider=Oracle.DataAccess.Client;provider connection string="DATA SOURCE=localhost/InceptaMSFA;PASSWORD=bs23;PERSIST SECURITY INFO=True;USER ID=BS"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
My client app is console app in C#
main program
class Program
{
static void Main(string[] args)
{
var client = new SyncServiceClient();
var db = new InceptaDbContext();
var order = client.InsertOrderData(1.0m);
foreach (var s in order.OrderInfoList)
{
db.ORDER_INFO.Add(new ConsumeDataSyncService.DbContext.ORDER_INFO
{
ORDER_ID = s.ORDER_ID,
CH_ID = s.CH_ID,
D_ID = s.D_ID,
EMP_ID = s.EMP_ID,
ORDER_DATE = s.ORDER_DATE,
ORDER_TYPE = s.ORDER_TYPE,
PAY_OPTION = s.PAY_OPTION,
PRODUCT_COUNT = s.PRODUCT_COUNT,
STATUS = "2"
});
Console.WriteLine(s.ORDER_ID +"Inserted");
}
foreach (var s in order.OrderProductMappingList)
{
var orderProductMapping = new ConsumeDataSyncService.DbContext.ORDER_PRODUCT_MAPPING
{
ID = s.ID,
ORDER_ID = s.ORDER_ID,
P_CODE = s.P_CODE,
QUANTITY = s.QUANTITY
};
db.ORDER_PRODUCT_MAPPING.Add(orderProductMapping);
Console.WriteLine(s.ID + "Inserted");
}
db.SaveChanges();
Console.ReadKey();
}
}
and app.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ISyncService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8092/SyncService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ISyncService" contract="OrderSyncService.ISyncService" name="BasicHttpBinding_ISyncService" />
</client>
</system.serviceModel>
<connectionStrings>
<add name="InceptaDbContext" connectionString="metadata=res://*/DbContext.Model1.csdl|res://*/DbContext.Model1.ssdl|res://*/DbContext.Model1.msl;provider=Oracle.DataAccess.Client;provider connection string="DATA SOURCE=192.168.1.159/Incepta;PASSWORD=bs23;USER ID=BS"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
the error I got at the time of debugging
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.
The underlying connection was closed: The connection was closed unexpectedly.
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.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 ISyncService.InsertOrderData(Decimal depotId)
at SyncServiceClient.InsertOrderData(Decimal depotId)
Inner Exception:
The underlying connection was closed: The connection was closed unexpectedly.
at System.Net.HttpWebRequest.GetResponse()`enter code here`
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
Usually with this error, there seems to be a circular reference in the model so it can't be serialized. Enable tracing to see the service's log, where you can see what exception caused the service to unexpectedly close the connection.
Thanks everybody who gave me time .... I have solved this problem. In the OrderData class there are two properties and that are also another class. So I have added the attributes like [DataContract] in the classes(ORDER_INFO and ORDER_PRODUCT_MAPPING) and [DataMember] in the properties and solved my problem.
Try with by adding
[Serializable,DataContract()]
in above the class name.

Custom Binding consuming a weblogic webservice ws-security 1.2

I'm trying to consume a WebLogic webservice with ws-security 1.2.
In the WSDL, the security section is the following:
<wsp:UsingPolicy wssutil:Required="true"/>
<wsp1_2:Policy wssutil:Id="Wssp1.2-2007-SignBody.xml">
<ns1:SignedParts xmlns:ns1="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<ns1:Body/>
</ns1:SignedParts>
</wsp1_2:Policy>
<wsp1_2:Policy wssutil:Id="Wssp1.2-2007-Wss1.0-X509-Basic256.xml">
<ns2:AsymmetricBinding xmlns:ns2="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<wsp1_2:Policy>
<ns2:InitiatorToken>
<wsp1_2:Policy>
<ns2:X509Token ns2:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient">
<wsp1_2:Policy>
<ns2:WssX509V3Token10/>
</wsp1_2:Policy>
</ns2:X509Token>
</wsp1_2:Policy>
</ns2:InitiatorToken>
<ns2:RecipientToken>
<wsp1_2:Policy>
<ns2:X509Token ns2:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/Never">
<wsp1_2:Policy>
<ns2:WssX509V3Token10/>
</wsp1_2:Policy>
</ns2:X509Token>
</wsp1_2:Policy>
</ns2:RecipientToken>
<ns2:AlgorithmSuite>
<wsp1_2:Policy>
<ns2:Basic256/>
</wsp1_2:Policy>
</ns2:AlgorithmSuite>
<ns2:Layout>
<wsp1_2:Policy>
<ns2:Lax/>
</wsp1_2:Policy>
</ns2:Layout>
<ns2:IncludeTimestamp/>
<ns2:ProtectTokens/>
<ns2:OnlySignEntireHeadersAndBody/>
</wsp1_2:Policy>
</ns2:AsymmetricBinding>
<ns3:Wss10 xmlns:ns3="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<wsp1_2:Policy>
<ns3:MustSupportRefKeyIdentifier/>
<ns3:MustSupportRefIssuerSerial/>
</wsp1_2:Policy>
</ns3:Wss10>
</wsp1_2:Policy>
<wsp:Policy wssutil:Id="Wssp1.2-2007-Wsp1.5-EncryptBody.xml">
<ns4:EncryptedParts xmlns:ns4="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<ns4:Body/>
</ns4:EncryptedParts>
</wsp:Policy>
After a lot of search because I'm new in wcf I ended up into the following configuration:
<system.serviceModel>
<client>
<endpoint name="wssMutualCert_Client"
address="https://..."
binding="customBinding"
bindingConfiguration="custom1"
contract="MyWebService.WebServicesMainMethod"
behaviorConfiguration="MutualCertBehavior">
</endpoint>
</client>
<bindings>
<customBinding>
<binding name="custom1" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00">
<textMessageEncoding messageVersion="Soap11" writeEncoding="UTF-8" />
<security defaultAlgorithmSuite="Basic256"
authenticationMode="MutualCertificateDuplex"
includeTimestamp="True"
messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"
securityHeaderLayout="LaxTimestampLast" messageProtectionOrder="SignBeforeEncrypt">
<localClientSettings maxClockSkew="00:07:00" />
<localServiceSettings maxClockSkew="00:07:00" />
<secureConversationBootstrap>
<localClientSettings maxClockSkew="00:07:00" />
<localServiceSettings maxClockSkew="00:07:00" />
</secureConversationBootstrap>
</security>
<context protectionLevel="EncryptAndSign"/>
<httpsTransport requireClientCertificate="true" maxBufferPoolSize="20000000" maxBufferSize="20000000" maxReceivedMessageSize="20000000"/>
</binding>
</customBinding>
<ws2007HttpBinding>
<binding name="wssMutualCertBinding">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="Certificate"/>
<transport clientCredentialType="Certificate"/>
</security>
</binding>
</ws2007HttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="MutualCertBehavior">
<clientCredentials>
<serviceCertificate>
<defaultCertificate
findValue="XXXXX"
storeLocation="LocalMachine"
storeName="TrustedPeople" x509FindType="FindByThumbprint"/>
</serviceCertificate>
<clientCertificate
findValue="YYYYY"
storeLocation="LocalMachine"
storeName="TrustedPeople" x509FindType="FindByThumbprint"/>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<system.serviceModel>
My test appl looks like following:
static void Main(string[] args)
{
MyWebService.WebServicesMainMethodClient client = new WebServicesMainMethodClient("wssMutualCert_Client");
MyWebService.webRequest request = new webRequest();
ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback;
try
{
webResponse response = client.retrieve(request);
}
catch (Exception e)
{
throw e;
}
}
public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
And what ever change I try in my configuration I receive the following:
An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
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.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
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 Client.MyWebService.WebServicesMainMethod.retrieve(retrieve request)
I have been trying to find something helpfull almost 2 days now. I've searhed time sychonization issues, certs issues.
ANY IDEA OR RECOMMENDATION WOULD BE VERY HELPFULL.
Thank you all in advance.
The error means that SOAP request WCF sends is not compatible with the weblogic security configurations. Usually there are issues with timestamp WCF sends and password as a text, but often non-.Net services want Digest Mode. There is no easy solution. Read this and this. I did downgrade to WSE 3.0 to be able to send requests to Java based service. There is easier to achieve this.

Vague WCF Error on client side when processing a large object graph

I am calling a WCF service from a SharePoint site and getting an error on the client with below details, when relatively large object graph is returned.
On debugging the service I can see that is contructs the object correctly and the method returns the final object (that has the list of other objects) correctly. But I get exception on client side on the service method call.
Thie service/method works fine in most of the cases. Below are the service configurations (apologies for bad formatting)
Service Config:
<system.serviceModel>
<services>
<service behaviorConfiguration="StandardServiceBehaviour" name="Thd.K2.Web.DataServicesLibrary.Common.Services.AdminService">
<endpoint address="soap" binding="basicHttpBinding" name="AdminService" contract="Thd.K2.Web.DataServicesLibrary.Common.Interfaces.IAdminService" />
<endpoint address="mex" binding="mexHttpBinding" name="Metadata" contract="IMetadataExchange" kind="mexEndpoint" endpointConfiguration="" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="StandardServiceBehaviour">
<serviceMetadata httpsGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="customBinding" hostNameComparisonMode="StrongWildcard" receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00" maxReceivedMessageSize="1000000" maxBufferSize="1000000" maxBufferPoolSize="1000000" transferMode="Buffered" messageEncoding="Text" textEncoding="utf-8" bypassProxyOnLocal="false" useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="214748364" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="Transport" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding name="webBinding" bypassProxyOnLocal="true" useDefaultWebProxy="false" hostNameComparisonMode="WeakWildcard" sendTimeout="00:05:00" openTimeout="00:05:00" receiveTimeout="00:05:00" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647">
<readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" />
<security mode="Transport">
</security>
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
Client method to create service instance
public static TServiceType GetServiceClient<TServiceType>(ConnStringsType connectionStringType, Page callingPage)
where TServiceType : class
{
var spUrl = GetConnectionString(connectionStringType, callingPage);
var result = new BasicHttpBinding(BasicHttpSecurityMode.None);
if(spUrl.ToLower().StartsWith("https"))
{
result = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
}
result.MaxReceivedMessageSize = int.MaxValue - 1;
result.MaxBufferSize = int.MaxValue-1;
if (!string.IsNullOrEmpty(spUrl))
{
return (TServiceType)Activator.CreateInstance(typeof(TServiceType), result, new EndpointAddress(spUrl));
}
return null;
}
Error:
An error occurred while receiving the HTTP response to http://localhost:90/AdminService.svc/soap. 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.
Stack:
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.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 IAdminService.GetBlackoutPeriodsByDescription(String lang, String description)
at AdminServiceClient.GetBlackoutPeriodsByDescription(String lang, String description)
at EditBlackoutDates.LoadBlackout(String description)
I think this is about MaxItemsInObjectGraph property. Here is the answer to the similar problem.
#paramosh - Thanks a lot!!!
That did the trick. For others reference I was actually using a Non-RESTful WCF service. Hence I modified the solution as below
Calling below function before the web svc method call:
private void ExpandObjectGraphItems(AdminServiceClient svc)
{
var operations = svc.Endpoint.Contract.Operations;
foreach (var operation in operations)
{
var dataContractBehavior = operation.Behaviors.Find<System.ServiceModel.Description.DataContractSerializerOperationBehavior>();
if (dataContractBehavior != null)
{
dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
}
}
}
Added following attribute to service config:
<behavior name="StandardServiceBehaviour">
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>

WCF transport security, wsHttpBinding, message security in load balancer

I have a WCF service that uses message security over HTTPS using wsHttpBinding behind load balancer. When connects to the service on web browser via https, it works. However, Windowns forms client failed, using certificate over https,
Update
The request url is https, but after the exception saying http, below is exception tracing on server side:
For example: the request url is
https://www.server.com/wcf.svc'.
But it becomes
http://www.server.com:81/wcf.svc' on the server side. Is it the load balancer causing it.
System.ServiceModel.EndpointNotFoundException, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
There was no channel actively listening at 'http://www.server.com:81/wcf.svc'. This is often caused by an incorrect address URI. Ensure that the address to which the message is sent matches an address on which a service is listening.
Below is the WCF service config:
<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage="true" logMalformedMessages="true"
logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="false" />
</diagnostics>
<services>
<service behaviorConfiguration="verServiceBehaviour" name="ver.Service">
<endpoint address="ver" binding="wsHttpBinding" bindingConfiguration="wshttpbindingcfg"
contract="ver.Iver" behaviorConfiguration ="verEndpointBehaviour">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="mexhttpbinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="https://www.server.com/" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<mexHttpBinding>
<binding name="mexhttpbinding" />
</mexHttpBinding>
<wsHttpBinding>
<binding name="wshttpbindingcfg" maxReceivedMessageSize="2000000000" sendTimeout="00:10:00">
<readerQuotas maxStringContentLength="2000000000"/>
<reliableSession ordered="true" enabled="false" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Certificate" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="false" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="verEndpointBehaviour">
<instanceContextBehavior/>
<verInspectorBehavior/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="verServiceBehaviour">
<dataContractSerializer maxItemsInObjectGraph="100000000"/>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" trustedStoreLocation="LocalMachine" mapClientCertificateToWindowsAccount="false"/>
</clientCertificate>
<serviceCertificate
x509FindType="FindByThumbprint"
findValue="xxxx"
storeLocation="LocalMachine"
storeName="My"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Below is client config:
<configuration>
<appSettings>
<add key="CertificateSubjectName" value="subjectName"/>
</appSettings>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ver.IverHTTPS" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Certificate" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="false" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="https://www.server.com/wcf.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ver.IverHTTPS"
contract="ServiceReference.verIver" name="verEndPoint" />
</client>
</system.serviceModel>
</configuration>
below is code in client using certificate:
var proxyClient = new ServiceReference.VerIVerClient("verEndPoint");
proxyClient.ClientCredentials.ClientCertificate.SetCertificate(
System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser,
System.Security.Cryptography.X509Certificates.StoreName.My,
System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName,
subjectName");
proxyClient.CallService()
Below is exception received at client side:
System.ServiceModel.EndpointNotFoundException was unhandled
Message=There was no endpoint listening at https://ver20.server.com/wcf.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, 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 verClient.ServiceReference.verIver.GetClaimver(GetClaimverClaimApplication ClaimApplication)
at verClient.ServiceReference.verIverClient.GetClaimver(GetClaimverClaimApplication ClaimApplication) in D:\Projects\ver\verClient\Service References\ServiceReference\Reference.cs:line 11330
at verClient.verForm.PostXmlTover(GetClaimverClaimApplication ClaimApplication) in D:\Projects\ver\verClient\verForm.cs:line 1408
at verClient.verForm.PostButton_Click(Object sender, EventArgs e) in D:\Projects\ver\verClient\verForm.cs:line 34
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at verClient.Program.Main() in D:\Projects\ver\verClient\Program.cs:line 18
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.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Net.WebException
Message=The remote server returned an error: (404) Not Found.
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
InnerException:
Review the configuration of your load balancer, and make sure that the requests are being for warded to the correct host AND PORT number. If the port number you chose is not standard, make sure to adjust the IIS Site Binding and the base address of your service.
One important thing to understand about transport security is that it has to be configured on a "hop" by "hop" basis. In your example, you have two hops (client) -> (load balancer) and (load balancer) -> (server).
Securing your connection from the client to the load balancer doesn't automatically configure security from the load balancer to the server. You need to install and configure an ssl certificate on both the load balancer and the server.
Your initial https request ended up being an http request on the server, that is a good indication that you did not configure a secure channel between the load balancer and the server.
If you do not wish to secure the connection between the load balancer and the server, then expose your service without transport security. With this, you can still have the communication from the client to the load balancer (the first hop) on ssl.