I have two WCF services hosted separately in IIS 7. The first service is callable from outside and uses a WebHttpBinding with windows authentication. The second service is only called by the first one, using a WsDualHttpBinding.
When the first service is called, I can get the user's windows name from ServiceSecurityContext.Current.WindowsIdentity.Name. In the second service, that doesn't work and ServiceSecurityContext.Current.WindowsIdentity.Name is just IIS APPPOOL\DefaultAppPool.
I configured the WsDualHttpBinding to use windows authentication, but that didn't help. Here is the server-side configuration:
<wsDualHttpBinding>
<binding name="internalHttpBinding">
<security mode="Message">
<message clientCredentialType="Windows"/>
</security>
</binding>
</wsDualHttpBinding>
And here's the code in the first service to establish communication with the second service:
private WSDualHttpBinding binding = new WSDualHttpBinding();
private ChannelFactory<IMyService> factory;
public IMyService Contract { get; set; }
public MyServiceCallback Callback { get; set; }
public MyService(Uri uri)
{
EndpointAddress address = new EndpointAddress(uri);
Callback = new MyServiceCallback();
var instanceContext = new InstanceContext(Callback);
binding.Security.Mode = WSDualHttpSecurityMode.Message;
binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
factory = new DuplexChannelFactory<IMyService>(instanceContext, binding, address);
factory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
factory.Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
Contract = factory.CreateChannel();
// Call operations on Contract
}
How can I configure the first service to pass on the user's identity to the second service?
This seems to be a problem with pass-through authentication.
First, you need to be in a Active Directory environment.
Kerberos must be used for authentication, NTLM will not work. You can use klist to check this:
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/klist
Also see
https://blogs.msdn.microsoft.com/besidethepoint/2010/05/08/double-hop-authentication-why-ntlm-fails-and-kerberos-works/
for an explanation.
May be this SO article can help:
Pass Windows credentials to remote https WCF service
And this:
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/delegation-and-impersonation-with-wcf
After the server-side enables impersonation and the client-side has set up the windows credential,
ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
client.ClientCredentials.Windows.ClientCredential.UserName = "Test";
client.ClientCredentials.Windows.ClientCredential.Password = "123456";
We could retrieve the running Windows account by using the below code.
if (ServiceSecurityContext.Current.WindowsIdentity.ImpersonationLevel == TokenImpersonationLevel.Impersonation ||
ServiceSecurityContext.Current.WindowsIdentity.ImpersonationLevel == TokenImpersonationLevel.Delegation)
{
using (ServiceSecurityContext.Current.WindowsIdentity.Impersonate())
{
Console.WriteLine("Impersonating the caller imperatively");
Console.WriteLine("\t\tThread Identity :{0}",
WindowsIdentity.GetCurrent().Name);
Console.WriteLine("\t\tThread Identity level :{0}",
WindowsIdentity.GetCurrent().ImpersonationLevel);
Console.WriteLine("\t\thToken :{0}",
WindowsIdentity.GetCurrent().Token.ToString());
}
}
Please refer to the below example.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/impersonating-the-client
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/delegation-and-impersonation-with-wcf
Feel free to let me know if there is anything I can help with.
Related
I am completely new to this Microsoft Dynamics AX 2012 tool and WCF service. I have a self hosted WCF service, where it takes AX 2012 service wsdl URL, AX server domain name, user name and password as inputs and will try to download metadata of this wsdl url without any user authentication mechanism in place.
MY AX 2012 service WSDl URL below:
http://####:8##1/DynamicsAx/Services/TestService?wsdl ---> WSDLEndpoint
I am dynamically creating WSHttpBinding, MetadataExchangeClient and assigned all it's properties and passed my wsdl endpoint.
Below is my sample code :
var binding = new WSHttpBinding(SecurityMode.None) { MaxReceivedMessageSize = int.MaxValue, MaxBufferPoolSize = int.MaxValue };
var mexClient = new MetadataExchangeClient(binding)
{
ResolveMetadataReferences = true,
MaximumResolvedReferences = int.MaxValue,
OperationTimeout = TimeSpan.FromSeconds(TimeOutInSeconds),
HttpCredentials =
new NetworkCredential(Username, Password, Domain)
};
mexClient.GetMetadata(new Uri(WSDLEndpoint), MetadataExchangeClientMode.HttpGet);
Log.Info("Metadata successfully downloaded.");
But above code won't bother about user credentials validation, it directly downloads metadata out of the WSDL URL, but I am looking to validate user credentials and after successful authentication, will download metadata.
Please help me with some authentication approach to introduce on top of wshttpbinding that supports cross platforms.
I don’t fully understand your meaning. Are you trying to create a WCF service with custom username/password authentication? This requires that we configure a certificate on the server-side. I created an example, wishing it is instrumental for you.
Server-side.
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri("http://localhost:21011");
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Message;
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
using (ServiceHost sh = new ServiceHost(typeof(MyService), uri))
{
sh.AddServiceEndpoint(typeof(IService), binding, "");
ServiceMetadataBehavior smb;
smb = sh.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null)
{
smb = new ServiceMetadataBehavior()
{
HttpGetEnabled = true
};
sh.Description.Behaviors.Add(smb);
}
sh.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "5ba5022f527e32ac02548fc5afc558de1d314cb6");
Binding mexbinding = MetadataExchangeBindings.CreateMexHttpBinding();
sh.AddServiceEndpoint(typeof(IMetadataExchange), mexbinding, "mex");
sh.Opened += delegate
{
Console.WriteLine("Service is ready");
};
sh.Closed += delegate
{
Console.WriteLine("Service is clsoed");
};
sh.Open();
Console.ReadLine();
//pause
sh.Close();
Console.ReadLine();
}
}
}
[ServiceContract]
public interface IService
{
[OperationContract]
string Test();
}
public class MyService : IService
{
public string Test()
{
return DateTime.Now.ToString();
}
}
On the Client-side, we create a client proxy by adding service reference.
ServiceReference1.ServiceClient client = new ServiceClient();
client.ClientCredentials.UserName.UserName = "administrator";
client.ClientCredentials.UserName.Password = "abcd1234!";
var result = client.Test();
Console.WriteLine(result);
The configuration automatically generated on the client-side.
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IService">
<security>
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://10.157.13.69:21011/" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IService" contract="ServiceReference1.IService"
name="WSHttpBinding_IService">
<identity>
<certificate encodedValue="blabla… " />
</identity>
</endpoint>
</client>
</system.serviceModel>
In the above example, the client should provide username/password to be authenticated by the server so that call the remote service.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/message-security-with-a-user-name-client
Feel free to let me know if there is anything I can help with.
I have a .NET Core 2.0 application and need to call a WCF client from one of its controllers, and pass the user credentials for authentication.
Within the .net core app I created a reference for the WCF client using the Connected Services (WCF Web Service Reference Provider) and now in a process of configuring the call. Note that I can use the same endpoint form a 4.6 framework application without any problems.
Here's my code:
var binding = new BasicHttpBinding {Security = {Mode = BasicHttpSecurityMode.Transport}};
var address = new EndpointAddress("https://my-endpoint.asmx");
var client = new MyAppSoapClient(binding, address);
var credentials = CredentialCache.DefaultNetworkCredentials;
client.ClientCredentials.Windows.ClientCredential = credentials;
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
var response = client.GetStuff("param").Result;
I face a number of problems:
It has to be a https call
I need to pass the currently log in user credentials to the call
The current error I get is as follows:
The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate, NTLM'
Also the ConnectedService.json (created automativcally by WCF Web Service Reference Provider) has a predefined endpoint Uri.. I don't understand why I need to pass the address to the client manually (the code seems to be forcing me to do so).. ideally I'd like to get this dynamically amended in json depending on environment.
Thanks.
I noticed that you passed the current logged-in user as a Windows credential (which is also necessary for enabling impersonation), but you did not explicitly set the client credentials for the transport layer security.
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
Also the ConnectedService.json (created automativcally by WCF Web
Service Reference Provider) has a predefined endpoint Uri.. I don't
understand why I need to pass the address to the client manually (the
code seems to be forcing me to do so)
You can modify the method of automatic generation of proxy client to construct client proxy class (located in the reference.cs)
Modify the binding security
private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration)
{
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap))
{
System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding();
result.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport;
result.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
result.MaxBufferSize = int.MaxValue;
result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
result.MaxReceivedMessageSize = int.MaxValue;
result.AllowCookies = true;
return result;
}
Modify the endpoint.
private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration)
{
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap))
{
return new System.ServiceModel.EndpointAddress("http://10.157.13.69:8001/webservice1.asmx");
Construct the client proxy class.
ServiceReference1.WebService1SoapClient client = new WebService1SoapClient(WebService1SoapClient.EndpointConfiguration.WebService1Soap);
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
client.ClientCredentials.Windows.ClientCredential.UserName = "administrator";
client.ClientCredentials.Windows.ClientCredential.Password = "123456";
Feel free to let me know if there is anything I can help with.
My binding was missing the security Ntlm credential type (see below).
Problem solved.
var binding = new BasicHttpBinding {Security = {Mode = BasicHttpSecurityMode.Transport,
Transport = new HttpTransportSecurity(){ClientCredentialType = HttpClientCredentialType.Ntlm } }};
I have a WCF service which uses Windows Authentication to view Service Contract and a specfic method in a service is configured to be accessed only by a specific user UserX.
[PrincipalPermission(SecurityAction.Demand,Name="xxx\\UserA")]
In the client side, I need to access the above service method. If I am using a Web Reference -> I add the following
client = new WebRefLocal.Service1();
client.Credentials = new System.Net.NetworkCredential("UserA", "xxxxxx", "test");
But the above cannot be achieved in WCF Service Reference as Client Credentials are read-only. One best way I can achieve the above is Impersonation
https://msdn.microsoft.com/en-us/library/ff649252.aspx.
My question here is
Why ClientCredentials are made readonly in WCF?
How Network Credential work? Will they authenticate the Windows login in client side or server side?
Is there is any way I can achieve the above in WCF aswell without impersonation?
I've done something like this - hope it helps:
var credentials = new ClientCredentials();
credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Delegation;
credentials.Windows.ClientCredential = new System.Net.NetworkCredential("UserA", "xxxxxx", "test");
client.Endpoint.Behaviors.Remove<ClientCredentials>();
client.Endpoint.Behaviors.Add(credentials);
Used with a BasicHttpBinding with following security settings:
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" proxyCredentialType="Windows" />
</security>
One method you can use is to make use of ChannelFactory when calling the WCF service.
The following code was taken from one of my MVCprojects, hence it has someModelState` validation code, I'm sure you can modify it to suit your needs.
protected R ExecuteServiceMethod<I, R>(Func<I, R> serviceCall) {
R result = default(R);
ChannelFactory<I> factory = CreateChannelFactory<I>();
try {
I manager = factory.CreateChannel();
result = serviceCall.Invoke(manager);
} catch (FaultException<ValidationFaultException> faultException) {
faultException.Detail.ValidationErrors.ToList().ForEach(e => ModelState.AddModelError("", e));
} finally {
if (factory.State != CommunicationState.Faulted) factory.Close();
}
return result;
}
private ChannelFactory<I> CreateChannelFactory<I>() {
UserAuthentication user = GetCurrentUserAuthentication();
ChannelFactory<I> factory = new ChannelFactory<I>("Manager");
if (IsAuthenticated) {
factory.Credentials.UserName.UserName = user.UserName;
factory.Credentials.UserName.Password = user.Password;
}
BindingElementCollection elements = factory.Endpoint.Binding.CreateBindingElements();
factory.Endpoint.Binding = new CustomBinding(elements);
SetDataContractSerializerBehavior(factory.Endpoint.Contract);
return factory;
}
Given is a wcf rest service which runs with HttpClientCredentialType.Windows and enforces a user to authenticate via kerberos.
private static void Main(string[] args)
{
Type serviceType = typeof (AuthService);
ServiceHost serviceHost = new ServiceHost(serviceType);
WebHttpBinding binding = new WebHttpBinding();
binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
ServiceEndpoint basicServiceEndPoint = serviceHost.AddServiceEndpoint(typeof(IAuthService), binding, "http://notebook50:87");
basicServiceEndPoint.Behaviors.Add(new WebHttpBehavior());
Console.WriteLine("wcf service started");
serviceHost.Open();
Console.ReadLine();
}
public class AuthService : IAuthService
{
public List<string> GetUserInformation()
{
List<string> userInfo = new List<string>();
userInfo.Add("Environment.User = " + Environment.UserName);
userInfo.Add("Environment.UserDomain = " + Environment.UserDomainName);
if (OperationContext.Current != null && OperationContext.Current.ServiceSecurityContext != null)
{
userInfo.Add("WindowsIdentity = " + OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name);
userInfo.Add("Auth protocol = " + OperationContext.Current.ServiceSecurityContext.WindowsIdentity.AuthenticationType);
}
else
{
userInfo.Add("WindowsIdentity = empty");
}
WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
return userInfo;
}
}
[ServiceContract]
public interface IAuthService
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "test/")]
List<string> GetUserInformation();
}
When i run this as a console application, and then open the website http://notebook50:87/test/ in internet explorer from another computer, i get a 'bad request' response.
I did enable kerberos logging, and it shows me KDC_ERR_PREAUTH_REQUIRED
I can solve this problem by creating a windows service, and run it under 'Local System account'.
In this case, a client is able to authenticate.
Question: What permission/settings does a user(which runs this wcf service) need in order to get the same behavior as when the application is running as windows service under local system?
Is this related with the Service Principle Name?
It is working now.
It really was a problem with the SPN
At the beginning, I've set the SPN like setpn -A HTTP/notebook50.foo.com, and with this, the kerberos authentication didn't work.
Now, i've set it like setspn -A HTTP/notebook50.foo.com username where username is the user under which the service runs.
From the SPN documentation i've read, it was not clear to me that i have to set the user account in this way.
It would be great if one could explain what happens here, and probably a link to a documentation for this scenario.
You can stop this error pops up via enable the "Do not require Kerberos preauthentication" option for that user account in Active directory users & computers -> properties -> account.
I am trying to consume a self-hosted WCF application using SSL and a custom authentication validator from within an integration test. So far I am able to self-host the service but I am not able to figure out how to consume it.
Here is the self-hosting code (it is not dependent on Web.Config, as far as I know):
[ClassInitialize]
public static void TestClassInitialize(TestContext testContext)
{
const string serviceAddress = "https://localhost/SelfHostedService";
Uri _svcEndpointUri = new Uri(serviceAddress);
var binding = new WSHttpBinding
{
Security =
{
Mode = SecurityMode.TransportWithMessageCredential,
Message = {ClientCredentialType = MessageCredentialType.UserName}
}
};
ServiceDebugBehavior debugBehavior = new ServiceDebugBehavior
{
IncludeExceptionDetailInFaults = true
};
MyServiceApi _api = new MyServiceApi();
ServiceHost _svcHost = new ServiceHost(_api, _svcEndpointUri);
_svcHost.Description.Behaviors.Remove<ServiceDebugBehavior>();
_svcHost.Description.Behaviors.Add(debugBehavior);
// Ensure that SSL certificate & authentication interceptor get used
ServiceCredentials credentials = new ServiceCredentials();
credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new MyCustomAuthenticationValidator();
credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "SubjectName");
_svcHost.Description.Behaviors.Remove<ServiceCredentials>();
_svcHost.Description.Behaviors.Add(credentials);
// Add IUbiquity and mex endpoints
Uri endpointAddress = new Uri(serviceAddress + "/UbiquityApi.svc");
_svcHost.AddServiceEndpoint(typeof (IUbiquityApi), binding, endpointAddress);
// Specify InstanceContextMode, which is required to self-host
var behavior = _svcHost.Description.Behaviors.Find<ServiceBehaviorAttribute>();
behavior.InstanceContextMode = InstanceContextMode.Single;
_svcHost.Open();
}
What I'd like to be able to do looks like this, but I have no idea how I'd go about accomplish this:
[TestMethod]
public void TestAuthentication(){
var api = _svcHost.MagicallyRetrieveServiceInstance();
api.Credentials = new MagicCredentials("my username", "my password");
Assert.AreEqual(3, api.AddNumbers(1,2));
// Also assert that I am authenticated
api.Credentials = new MagicCredentials("my username", "my password");
bool exceptionWasThrown = false;
try {
api.AddNumbers(1,2);
}
catch(NotLoggedInException l){ // or something
exceptionWasThrown = true;
}
Assert.IsTrue(exceptionWasThrown);
}
My ideal solution would allow me to retrieve the service contract from the service host, and allow me to set the credentials used for the service contract. I should only have to supply the credentials once to the service contract, and then I should be able to call methods directly, as if I were communicating over the wire (thus making this an integration test). How should I go about this?
To consume the web service, simply add the service as a service reference, and then use the service reference client.
Done right, this will take care of the bindings needed for authentication, effectively putting the WCF configurations under test.