Object values defaulting - c#

I converted my WCF Services today to use WSHttpBinding instead of BasicHttpBinding. It is still in the development stage and thus I am using self signed certificates. The example that I followed is located Here
After finally getting the code to work like the example illustrates (follow the examples of the configs in the code that one can download), I decided to proceed to use Channel Factories like I did before.
Now when I make a call to a WCF method, I can clearly see that the object that I am sending is populated with the expected values, but if I step into the WCF side, the values are their defaults. For example Guid's will be Empty Guid's and int's will be 0. Always.
Any idea what might be causing this? here is some of my code:
In the web.config:
<add key="ClientCertificate" value="WcfClient" />
<add key="ServerCertificate" value="WcfServer" />
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="CustomBehavior">
<clientCredentials>
<clientCertificate findValue="WcfClient"
x509FindType="FindBySubjectName"
storeLocation="CurrentUser"
storeName="My" />
<serviceCertificate>
<authentication certificateValidationMode="PeerTrust"/>
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IDocumentsService" closeTimeout="00:10:00"
openTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647" messageEncoding="Mtom" allowCookies="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Certificate" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:58790/DocumentsService.svc"
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IDocumentsService"
contract="DocumentsService.IDocumentsService"
name="WSHttpBinding_IDocumentsService"
behaviorConfiguration="CustomBehavior">
<identity>
<dns value="WcfServer" />
</identity>
</endpoint>
</client>
</system.serviceModel>
This is my channel factory
public static class ServiceObjects
{
public static IDocumentsService DocumentsSVC { get { return GetDocServiceClient(); } }
#region Private Members
private static WSHttpBinding _DMBinding = new WSHttpBinding("WSHttpBinding_IDocumentsService");
private static EndpointIdentity _DMIdentity = EndpointIdentity.CreateDnsIdentity(ConfigurationManager.AppSettings.Get("ServerCertificate"));
private static EndpointAddress _DMEndpoint = new EndpointAddress(new Uri(ConfigurationManager.AppSettings.Get("DocumentsService")), _DMIdentity);
private static IDocumentsService GetDocServiceClient()
{
ChannelFactory<IDocumentsService> _docSvcFactory = new ChannelFactory<IDocumentsService>(_DMBinding, _DMEndpoint);
_docSvcFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust;
_docSvcFactory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, ConfigurationManager.AppSettings.Get("ClientCertificate"));
_docSvcFactory.Credentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, ConfigurationManager.AppSettings.Get("ServerCertificate"));
return _docSvcFactory.CreateChannel();
}
#endregion
}
When I call the service, on the Client side for example:
private static Guid _UserID = (HttpContext.Current.User as Titan.Web.Classes.Identity.CustomPrincipal).UserId;
ServiceObjects.DocumentsSVC.GetDocumentsByFolderID(new DocumentRequest { CurrentUserID = _UserID })
I can see _UserID is populated, but on the server side it's not.
This is in my service's config
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="wsHttpEndpointBinding" closeTimeout="00:10:00" openTimeout="00:10:00" sendTimeout="00:10:00" allowCookies="true" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Mtom">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security>
<message clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="Titan.WCF.Documents.DocumentsService" behaviorConfiguration="DocumentsServiceBehavior">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpEndpointBinding" contract="Titan.WCF.Documents.IDocumentsService">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="DocumentsServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<serviceCredentials>
<clientCertificate>
<!-- Remove the NoCheck in production, this is only for when we use a self signed cert -->
<authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" />
</clientCertificate>
<serviceCertificate findValue="WCfServer"
storeLocation="CurrentUser"
storeName="My"
x509FindType="FindBySubjectName" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Of course, since you've changed your configuration in the service you need to update the service reference so that the client too can update its configuration on its side. Unless you do that the client will keep calling the service with old configuration which it reads from its config file while the service runs with the new configuration settings.
It may be tiring, but it's the way it is.

It seems the issue lies in the way you make a call to the service using the following code:
ServiceObjects.DocumentsSVC.GetDocumentsByFolderID(new DocumentRequest { CurrentUserID = _UserID });
Here you are trying to invoke the service function without creating a proxy object of the service. And that is because you have written a static class in the service.
In a WCF service you can't use static classes. You need to create an instance of the class (service proxy object) and then invoke the service function.

I am not sure why this would make a difference, but it did.
I needed to update my service references.
A rookie mistake I guess, but why would that make a difference if the only thing I did was to change the bindings, endpoints etc?

Related

Set max time skew in wcf with net.tcp binding

I have a WCF service with net.tcp endpoints using custom usernamePassswordValidator, custom authorization and TransportWithMessageCredential with credential type "Username" (see below).
Server and client work fine - unless the time skew between server and client machine are more than 5 minutes.
Now I try to set the max skew time in code. I tried to adapt code snippets intended for WSHttpBindings from MSDN and used the custom binding on server and client:
binding = GetSecuredBindingFromServerOrClient();
CustomBinding myCustomBinding = new CustomBinding(binding);
var security = myCustomBinding.Elements.Find<TransportSecurityBindingElement>(); // TransportSecurityBindingElement or SecurityBindingElement
security.LocalClientSettings.MaxClockSkew = timeSkew;
security.LocalServiceSettings.MaxClockSkew = timeSkew;
security.LocalServiceSettings.DetectReplays = false;
security.IncludeTimestamp = false;
// on client: use this custom binding in channel factory
var channelFactory = new ChannelFactory<ICheckerService>(customBinding, someAddress);
// on server: Update binding with customBinding
endpoint.Binding = myCustomBinding;
Still the connection fails with a MessageSecurityException when there is a time skew for more than 5 minutes (default value). I set also IncludeTimestamp to false or true but neither of them improved the situation.
The server behavior is:
<behavior name="customUserNamePasswordSecurityBehavior">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MySecurity.BasicAuthenticationValidator, MySecurity.Services"/>
</serviceCredentials>
<serviceAuthorization principalPermissionMode="Custom">
<authorizationPolicies>
<add policyType="Security.CustomAuthorizationPolicy, MySecurity.Services"/>
</authorizationPolicies>
</serviceAuthorization>
</behavior>
Then endpoint bindings are:
<binding name="tcpUserNameAuthentication">
<reliableSession enabled="true"/>
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
</binding>
Did anybody get the time skew working based on the above configuration with TransportWithMessageCredential and net.tcp? Or is there a basic misunderstanding?
On my side, MaxClockSkew works well if I use NetTcp protocol, which requires a certificate on the server-side (need to add the management permission of the private key to the account running the service) and username/password on the client-side.
At first, I transform the Nettcpbinding to Custombinding.
<customBinding>
<binding name="mybinding">
<security authenticationMode="SecureConversation">
<localClientSettings maxClockSkew="00:07:00" />
<localServiceSettings maxClockSkew="00:07:00" />
<secureConversationBootstrap authenticationMode="UserNameForCertificate">
<localClientSettings maxClockSkew="00:30:00" />
<localServiceSettings maxClockSkew="00:30:00" />
</secureConversationBootstrap>
</security>
<binaryMessageEncoding></binaryMessageEncoding>
<tcpTransport />
</binding>
</customBinding>
Then I invocate the service with the client proxy class when I change the time on the client-side, it works well when the client time varies within 7minutes on the server-side. if I didn't set up the MaxClockSkew on the server-side. it only works within 5minutes the server-side time.
Please refer to the below example, wish it is useful to you.
Server-side(console application)
class Program
{
static void Main(string[] args)
{
using (ServiceHost sh=new ServiceHost(typeof(MyService)))
{
sh.Open();
Console.WriteLine("Service is ready....");
Console.ReadLine();
sh.Close();
}
}
}
[ServiceContract]
interface IService
{
[OperationContract]
string GetData();
}
public class MyService : IService
{
public string GetData()
{
return DateTime.Now.ToString();
}
}
public class MyValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (userName != "jack" || password != "123456")
{
throw new Exception("My Error");
}
}
}
App.config
<system.serviceModel>
<services>
<service name="Server1.MyService" behaviorConfiguration="mybehavior">
<endpoint address="" binding="customBinding" contract="Server1.IService" bindingConfiguration="mybinding"></endpoint>
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"></endpoint>
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:800"/>
</baseAddresses>
</host>
</service>
</services>
<bindings>
<customBinding>
<binding name="mybinding">
<security authenticationMode="SecureConversation">
<localClientSettings maxClockSkew="00:07:00" />
<localServiceSettings maxClockSkew="00:07:00" />
<secureConversationBootstrap authenticationMode="UserNameForCertificate">
<localClientSettings maxClockSkew="00:30:00" />
<localServiceSettings maxClockSkew="00:30:00" />
</secureConversationBootstrap>
</security>
<binaryMessageEncoding></binaryMessageEncoding>
<tcpTransport />
</binding>
</customBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="mybehavior">
<serviceMetadata />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<serviceCertificate findValue="5ba5022f527e32ac02548fc5afc558de1d314cb6" x509FindType="FindByThumbprint" storeLocation="LocalMachine" storeName="My"/>
<userNameAuthentication customUserNamePasswordValidatorType="Server1.MyValidator,Server1" userNamePasswordValidationMode="Custom"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Client-side.
ServiceReference1.ServiceClient client = new ServiceClient();
client.ClientCredentials.UserName.UserName = "jack";
client.ClientCredentials.UserName.Password = "123456";
try
{
var result = client.GetData();
Console.WriteLine(result);
}
catch (Exception)
{
throw;
}
App.config(auto-generated)
<system.serviceModel>
<bindings>
<customBinding>
<binding name="CustomBinding_IService">
<security defaultAlgorithmSuite="Default" authenticationMode="SecureConversation"
requireDerivedKeys="true" includeTimestamp="true" messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"
requireSignatureConfirmation="false" canRenewSecurityContextToken="true">
<secureConversationBootstrap defaultAlgorithmSuite="Default"
authenticationMode="UserNameForCertificate" requireDerivedKeys="true"
includeTimestamp="true" messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"
requireSignatureConfirmation="false">
<localClientSettings detectReplays="true" />
<localServiceSettings detectReplays="true" />
</secureConversationBootstrap>
<localClientSettings detectReplays="true" />
<localServiceSettings detectReplays="true" />
</security>
<binaryMessageEncoding />
<tcpTransport />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="net.tcp://10.157.13.69:800/" binding="customBinding"
bindingConfiguration="CustomBinding_IService" contract="ServiceReference1.IService"
name="CustomBinding_IService">
<identity>
<certificate encodedValue="blablabla" />
</identity>
</endpoint>
</client>
</system.serviceModel>
Feel free to let me know if there is anything I can help with.

Rename WCF Service Name & Binding Name

Assumption:
I'm working with a WCF application called DemoWCF, in which I have a simple wcf service called Calculator.
The purpose of the application is obviously a demo, the WCF service has to take two numbers as parameters and make the sum of them.
Service Class:
public class Calculator : ICalculator
{
public int Sum(int firstValue, int secondValue)
{
return firstValue + secondValue;
}
}
Service Contract :
[ServiceContract(Namespace="http://ROCKET/Calculator")]
public interface ICalculator
{
[OperationContract]
int Sum(int firstValue, int secondValue);
}
Web.config, service model configuration:
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="wsHttpsBinding">
<security mode="Transport">
<transport clientCredentialType="None"></transport>
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="DemoWCF.Services.ServiceClasses.Calculator">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpsBinding" contract="DemoWCF.Services.ServiceContracts.ICalculator" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<serviceMetadata httpsGetEnabled="true" httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
When I deploy the WCF application on my IIS and I try to consume the WCF service in SOAP UI or in an ASP.NET MVC application, everything works fine.
Goal:
When I consume the WCF service in SOAP UI, I note that from the wsdl of the web service is automatically generated the binding "WSHttpBinding_ICalculator".
When I consume the WCF service in an ASP.NET MVC application, I note that the from the wsdl of the web service is automatically generated the service model, precisely:
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ICalculator">
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="https://rocket/ServiceClasses/Calculator.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ICalculator" contract="Calculator.ICalculator" name="WSHttpBinding_ICalculator" />
</client>
</system.serviceModel>
What I want to do, is to rename the Service Name and the Binding Name of the WCF Service.
It's possibile to omit this WCF behavior of generating binding's name with the format : "BindingType_IServiceInterface" ?
What I have to do, if I want to rename my service name and binding name in "Calculator" ?

Make Wcf Service IntegratedWindowsAuthentication

I m getting the following error when I did set the Windows Authentication enable and anonymous to disabled in IIS.
The authentication schemes configured on the host
('IntegratedWindowsAuthentication') do not allow those configured on
the binding 'BasicHttpBinding' ('Anonymous'). Please ensure that the
SecurityMode is set to Transport or TransportCredentialOnly.
Additionally, this may be resolved by changing the authentication
schemes for this application through the IIS management tool, through
the ServiceHost.Authentication.AuthenticationSchemes property, in the
application configuration file at the
element, by updating the ClientCredentialType property on the
binding, or by adjusting the AuthenticationScheme property on the
HttpTransportBindingElement.
My Wcf Service's web.config is as follows...
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint binding="basicHttpBinding"
bindingConfiguration="BasicHttpEndpointBinding"
contract="Test.IService1" name="BasicHttpEndpoint" />
</client>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceAuthenticationManager
authenticationSchemes="IntegratedWindowsAuthentication"/>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"/>
<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"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Please advice..
In .Net 4.0+, Simplified WCF configuration uses the 'anonymous' configurations when configurations are not explicitly set on a per-services basis in the <services> section. If you remove the name="BasicHttpEndpointBinding" from the <binding> element, or if you duplicate that <binding> element as a new element with no name attribute, it will become the default, anonymous binding that your WCF services will use. This is often useful in cases where you need to serve as well as consume WCF services that may not all have the same config - but at least you can set a default config for the services that do not have a specific config set. The default/anonymous concept is also applicable to <behavior> elements.
<bindings>
<basicHttpBinding>
<binding> <!--Notice, no name attribute set-->
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
Also, I might add that if your WCF services require authentication, this means that you will either need to consume the service using a real user account, or you will need to grant the the DOMAIN\CLIENTCOMPUTERNAME$ account access to the service - so, perhaps the proper solution for many people may be to alter the configuration to instead allow anonymous access (which is not discussed in my answer). Still, I do sometimes actually elect to secure my WCF services with Windows (Kerberos) authentication.
Adding this worked for me.
<bindings>
<webHttpBinding>
<binding>
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</webHttpBinding>
</bindings>
I got this error when updating from .NET 4.0 to .NET 4.5.2. I changed the clientCredentialType from
<security mode="TransportCredentialOnly">
<transport clientCredentialType="None"/>
</security>
to
<security mode="TransportCredentialOnly">
<transport clientCredentialType="InheritedFromHost"/>
</security>
However, setting clientCredentialType="Windows" works equally well.
I had the same issue when consuming already existing WCF web URL.
I tried all the answers mentioned here , but all in all finally only two things helped.
Changing the setting in "Turn windows Features on and off".
Enabling Anonymous authentication along with Windows Authentication in Local IIS server.
<services>
<service name="Test.Service1" behaviorConfiguration="TestName">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpEndpointBinding" contract="Test.IService1" />
</service>
</services>
It solved my problem.
Like the other answers, I needed to update the binding in my Web.config to this:
<basicHttpBinding>
<binding name="basicHttpBindin1">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
But I also needed to update my binding's instantiation:
var binding = new BasicHttpBinding { MaxReceivedMessageSize = 1000000, ReaderQuotas = { MaxDepth = 200 } };
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
I had add a webHttpBinding and point my endpoint to that, which the security settings needed to work. Without that my endpoint used the default WCF config bindings:
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="" binding="webHttpBinding" contract="IService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<bindings>
<webHttpBinding>
<binding>
<!--Notice, no name attribute set-->
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</webHttpBinding>
</bindings>
I'm not entirely sure why, but when I added the 'Factory' attribute to my .SVC file (you need to explicitly drag it to Visual Studio), everything just works - without any changes to default settings in Web.config!
I added Factory="System.ServiceModel.Activation.WebServiceHostFactory" so my .SVC file went from this:
<%# ServiceHost Language="C#" Debug="true" Service="ServiceNameSpace.ServiceName" CodeBehind="ServiceName.svc.cs" %>
to this:
<%# ServiceHost Language="C#" Debug="true" Service="ServiceNameSpace.ServiceName" CodeBehind="ServiceName.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
The only side effect seems to be that when you click on the .SVC file in the browser, you get an 'Endpoint not found' error, but the service works fine when you invoke it correctly anyway. As mentioned previously, I'm using a default Web.config with .NET 4.6 (Simplified WCF configuration), so I may yet need to add endpoint details for that to work again.

Impersionation like in ASP.NET for WCF Service

I've got a WebService with ASP.NET sites and WCF services in the same web.config. Until now, I was able to use the ASP.NET impersionation in the WCF services by setting
<system.web>
<compilation targetFramework="4.0" debug="false"/>
<!-- switch custom errors of-->
<identity impersonate="true"/>
<customErrors mode="Off"/>
</system.web>
However, now (for other reasons-> Cookieless Session state for the ASP.NET part) I have to set the
aspNetCompatibilityEnabled="true"
option to false. With this I loose the ASP.NET impersionation for the WCF services.
One of my WCF services needs impersionation for IO operations on the server...
I would like to know how to get the same impersionation I had before by directly defining it on the WCF service configuration.
What I have tried (unsucessfully) is to set
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
on the implementation of the methods in the WCF service and then specifying
<endpoint address="" binding="wsHttpBinding" contract="IService">
<identity>
<servicePrincipalName value="HOST/YourMachineName" />
<dns value="" />
</identity>
</endpoint>
in the web.config (obviously with the correct values for my service), as described in http://msdn.microsoft.com/en-us/library/ff650591.aspx.
However, the WCF service can not be called anymore after this... It tells me that the WsHttpBinding does not offer an identity for the contract.
Am I missing something important?
Edit: Translation of the error message:
: The contract operation '{0}' requires Windows identity for automatic impersonation. A Windows identity that represents the caller is not provided by binding ('{1}','{2}') for contract ('{3}','{4}'.
(The original error message was german...)
Try adding someting similar to this
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="DelegationBehaviour">
<clientCredentials>
<windows allowNtlm="false" allowedImpersonationLevel="Delegation"></windows>
</clientCredentials>
<dataContractSerializer maxItemsInObjectGraph="4194304"></dataContractSerializer>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_SampleWebService" >
<readerQuotas maxArrayLength="16384" maxBytesPerRead="4096" maxDepth="32" maxNameTableCharCount="16384" maxStringContentLength="8192"></readerQuotas>
<security mode="TransportCredentialOnly">
<message algorithmSuite="Default" clientCredentialType="UserName"></message>
<transport clientCredentialType="Windows" proxyCredentialType="None" realm=""></transport>
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://server/WebServices/Service/Service.svc" behaviorConfiguration="DelegationBehaviour" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_SampleWebService" contract="SampleWS" name="BasicHttpBinding_SampleEndpoint"></endpoint>
</client>
</system.serviceModel>
This is the server side code
<system.serviceModel>
<services>
<service behaviorConfiguration="CustomBehavior" name="CustomWebService">
<endpoint address="" behaviorConfiguration="" binding="basicHttpBinding" bindingConfiguration="basicHttpBinding_Service" contract="WebService"/>
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBinding_Service" maxReceivedMessageSize="4194304" receiveTimeout="00:30:00">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="CustomBehavior">
<dataContractSerializer maxItemsInObjectGraph="4194304" ignoreExtensionDataObject="True"/>
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true"/>
<serviceAuthorization impersonateCallerForAllOperations="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
As well as having these over our WebMethods
<WebMethod(), OperationContract(), OperationBehavior(Impersonation:=ImpersonationOption.Required)> _
Works for us
Well, in the end I just made the binding use Windows authentication:
<security mode="TransportWithMessageCredential">
<message negotiateServiceCredential="false" clientCredentialType="Windows" algorithmSuite="Default"/>
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
</security>
and passed a specific Windows user/pwd combination in the client:
channelFactory.Credentials.Windows.ClientCredential = new NetworkCredential(#"", "", "");
channelFactory.Credentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
Additionally I had to specifically use the newly impersonated user in the code of the web service:
using (var imp = ServiceSecurityContext.Current.WindowsIdentity.Impersonate())
{
// do IO here
}
Well, the actual (underlying) question still remains:
How is it possible to emulate the ASP.NET functionality correctly...
For the moment I'm ok with the solution, however I've got the feeling that I've missed an important point about the ASP.NET impersonation.
Thanks a lot to Iain, although it wasn't exactly the correct answer, it at least got me on the right track!

WCF wsHttpBinding 'algorithmSuite' cannot be parsed error

I am using VSTS 2008 + C# + .Net 3.0. I am using self-hosted WCF. When executing the following statement (host.Open()), there is the following binding not found error. I have posted my whole app.config file, any ideas what is wrong?
ServiceHost host = new ServiceHost(typeof(MyWCFService));
host.Open();
Error message,
The value of the property 'algorithmSuite' cannot be parsed. The error is: The value 'Aes128' is not a valid instance of type 'System.ServiceModel.Security.SecurityAlgorithmSuite'.
EDIT1: I have changed the algorithm suit option value to Default, but met with a new error when executing Open(), error message is, any ideas what is wrong,
Binding validation failed because the WSHttpBinding does not support reliable sessions over transport security (HTTPS). The channel factory or service host could not be opened. Use message security for secure reliable messaging over HTTP.
Full app.config,
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="MyBinding"
closeTimeout="00:00:10"
openTimeout="00:00:20"
receiveTimeout="00:00:30"
sendTimeout="00:00:40"
bypassProxyOnLocal="false"
transactionFlow="false"
hostNameComparisonMode="WeakWildcard"
maxReceivedMessageSize="100000000"
messageEncoding="Mtom"
proxyAddress="http://foo/bar"
textEncoding="utf-16"
useDefaultWebProxy="false">
<reliableSession
enabled="false" />
<security mode="Transport">
<transport clientCredentialType="Digest"
proxyCredentialType="None"
realm="someRealm" />
<message clientCredentialType="Windows"
negotiateServiceCredential="false"
algorithmSuite="Default"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="MyWCFService"
behaviorConfiguration="mexServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="https://localhost:9090/MyService"/>
</baseAddresses>
</host>
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="MyBinding" contract="IMyService"/>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="mexServiceBehavior">
<serviceMetadata httpsGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>
thanks in advance,
George
You need to update your service behavior, too, if you change the MEX endpoint from http to https - you need to enable the httpsGetEnabled setting (not the httpGetEnabled):
<behaviors>
<serviceBehaviors>
<behavior name="mexServiceBehavior">
<serviceMetadata httpsGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
UPDATE:
George, check out this MSDN link - there is no "Aes128" algorithm - you must pick one of the existing ones.
UPDATE 2:
Can you try this config - reduce to the max! :-)
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="MyBinding"
maxReceivedMessageSize="100000000"
messageEncoding="Mtom"
proxyAddress="http://foo/bar"
textEncoding="utf-16"
useDefaultWebProxy="false">
<reliableSession enabled="false" />
<security mode="None" />
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="MyWCFService"
behaviorConfiguration="mexServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="https://localhost:9090/MyService"/>
</baseAddresses>
</host>
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="MyBinding" contract="IMyService"/>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="mexServiceBehavior">
<serviceMetadata httpsGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Can you start up your service,and can you add service reference from Visual Studio?
UPDATE 3:
George, I'd recommend you have a look at those security-related links and get some feel for what you really need and want - and how to achieve it.
WCF Security Guide
WCF Security Fundamentals
Fundamentals of WCF Security
MSDN Webcast Series "WCF Top To Bottom"
esp. Episode 10 - Security Fundamentals
Marc
The error message is correct, you don't get reliable messages over WSHttp, you need to use a custom binding and protocol.

Categories

Resources