Set max time skew in wcf with net.tcp binding - c#

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.

Related

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

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

How to call a service using multiple Endpoint URIs

To put into context, I have a client application that will attempt to call a webservice that will be deployed on multiple web servers. The URI list will be obtained from the Settings.settings file of the client and a foreach loop will cycle through the URIs until the available service responds.
Let's say I have a service with the following contract:
[ServiceContract]
public interface ICMMSManagerService
{
[OperationContract]
ServerInfo GetServerInfo(string systemNumber);
}
In the web.config of the service's project, I have defined CMMSManager service with the the endpoint name: BasicHttpBinding_IWorkloadMngrService
<system.serviceModel>
<services>
<service name="WorkloadMngr">
<endpoint binding="basicHttpBinding" contract="IMetadataExchange" />
</service>
<service name="CMMSManager">
<endpoint binding="basicHttpBinding" contract="IMetadataExchange" name="BasicHttpBinding_IWorkloadMngrService" />
</service>
</services>
<client>
<remove contract="IMetadataExchange" name="sb" />
</client>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding>
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
On the client side, I have the following code executed when the application starts:
private void QueryWebServiceUrls()
{
var webServiceUrls = Properties.Settings.Default.WebServiceUrls;
foreach (var webServiceUrl in webServiceUrls)
{
try
{
var client = new CMMSManagerServiceClient("BasicHttpBinding_IWorkloadManagerService");
client.Endpoint.Address = new EndpointAddress(new Uri(webServiceUrl),
client.Endpoint.Address.Identity, client.Endpoint.Address.Headers);
client.Open();
var result = client.GetServerInfo("test");
}
catch (EndpointNotFoundException e)
{
continue;
}
catch (InvalidOperationException e)
{
break;
}
}
}
But the application crashes with an InvalidOperationException when the CMMSManagerServiceClient class is instanciated.
Could not find endpoint element with name
'BasicHttpBinding_IWorkloadMngrService' and contract
'ComClientService.ICMMSManagerService' in the ServiceModel client
configuration section. This might be because no configuration file was
found for your application, or because no endpoint element matching
this name could be found in the client element.
I have the following configuration in the app.config:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ICMMSManagerService">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost/WorkloadMngr/CMMSManagerService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ICMMSManagerService"
contract="ComClientService.ICMMSManagerService" name="BasicHttpBinding_ICMMSManagerService" />
</client>
</system.serviceModel>
I thought everything was valid by passing the BasicHttpBinding_ICMMSManagerService parameter to the CMMSManagerServiceClient class. I have no clue what am I missing at the moment... Any ideas?
The error is telling you exactly what's wrong: there is no endpoint with the name BasicHttpBinding_IWorkloadMngrService. The app.config says the endpoint is called BasicHttpBinding_ICMMSManagerService so your code should be:
var client = new CMMSManagerServiceClient("BasicHttpBinding_ICMMSManagerService");
Hope this helps.

Object values defaulting

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?

Validate Oauth Access Token in WCF Message Inspector

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

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!

Categories

Resources