How to authenticate in WCF services in BasicHttpBinding? - wcf

I am developing WCF services with basicHttpBinding, these services should be accessible using .net 1.1 & .net 2.0, for this purpose I am using basicHttpBinding. In old ASMX web services I assed one Soap Header (AuthHeader) to authenticate the user every request.How Can I authenticate in WCF using basicHttpBinding? Any sample Or tutorial will helpfull.
nRk

You can use AuthHeader as you did before switching to WCF. Maybe it will be more convinient for you, cause the princples will remain the same.
The bad thing i see in this solution is a plain text password transfer. Anyway, it's just another option and you can encrypt/decrypt the password somehow.
In this case you should implement your own your IDispatchMessageInspector & IClientMessageInspector, like
[AttributeUsage(AttributeTargets.Class)]
public class CredentialsExtractorBehaviorAttribute : Attribute, IContractBehavior, IDispatchMessageInspector
{
#region IContractBehavior implementation.
public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint,
DispatchRuntime dispatchRuntime)
{
dispatchRuntime.MessageInspectors.Add(this);
}
... empty interface methods impl skipped ...
#endregion
#region IDispatchMessageInspector implementation.
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
int i = request.Headers.FindHeader("username", "sec");
if (-1 != i)
{
string username = request.Headers.GetHeader<string>("username", "sec");
... do smth ...
}
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
return;
}
#endregion
}
In a sample i placed to header only username, but you can implement your a class containing username and password and use it instead of string.
On the client:
internal class CredentialsInserter : IContractBehavior, IClientMessageInspector
{
private string m_username;
public CredentialsInserter(string username)
{
m_username = username;
}
#region IContractBehavior implementation.
... empty interface methods impl skipped ...
public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint,
ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(this);
}
#endregion
#region IClientMessageInspector implementation.
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
MessageHeader<string> mh = new MessageHeader<string>(m_username);
request.Headers.Add(mh.GetUntypedHeader("username", "sec"));
return null;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
return;
}
#endregion
}
Then you should place attribute CredentialsExtractorBehaviorAttribute on your service implementation class.
[CredentialsExtractorBehavior]
public class DummyService : IDummyService
{
... impl ...
}
And on the client side you should do the following:
using (DummyServiceClient c = new DummyServiceClient("TcpEndpoint"))
{
c.ChannelFactory.Endpoint.Contract.Behaviors.Add(
new CredentialsInserter("_username_"));
c.DummyMethod();
}

First of all - yes you can! It depends on whether you use Transport or Message binding - if you're internet-facing, you're more likely to use message-based security.
Unfortunately, for message-based security, basicHttpBinding only supports certificates which is a bit of a pain.
wsHttpBinding on the other hand would support username/password or other methods as well.
You'd configure wsHttpBinding with username/password client credentials over message-based security like this:
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="wsUserName">
<security mode="Message">
<message clientCredentialType="UserName"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="yourservice">
<endpoint name="YourEndpoint"
address=""
binding="wsHttpBinding"
bindingConfiguration="wsUserName"
contract="IYourService" />
</service>
</services>
</system.serviceModel>
The section under <bindings> defines a binding configuration for wsHttpBinding that uses message-security with username/password client credentials.
The section under <service> defines a sample service that uses wsHttpBinding and that references that binding configuration that we just defined.
On the server side, you could now use the username/password that's being sent over the wire to validate your callers either in your Active Directory (everyone calling needs an AD account with you), or in the ASP.NET membership system database; or if you really really must, you could write your own authentication mechanism, too.
Find a lot of useful information on WCF security at Codeplex - excellent resource.

Check the scenarios here to try to match one to your situation. Each scenario is provided with a chceklist of items required to implement the solution.

Related

WCF Exception : ServiceHost only supports class service types -- when run from windows service

i am new in wcf. i am facing this error ServiceHost only supports class service types.
here i will say i am doing & running my win service & wcf together.
i added windows service project and also add few reference like System.ServiceModel for wcf in win service project. when i am trying to run wcf service from win service then i am getting error called ServiceHost only supports class service types
i search & got many answer like
ServiceHost host = new ServiceHost(
typeof(subservice.ISubService), new Uri("someuri"));
If this is your usage, change it to use the implemented service class type of ISubService
ServiceHost host = new ServiceHost(
typeof(subservice.SubService), new Uri("someuri"));
If configuring the service in .svc then:
<%#ServiceHost Service="subservice.SubService"%>
Also in you config file, change service name to the service instead of the service contract as:
<services>
<service name="subservice.SubService">
...
other search result also said very similar things to get rid of this problem.
i have no svc file for my wcf service. i have just one file where i have contract and service classes. i also have config file.
here i am giving the brief of my service code
namespace SageDataImportWCF
{
[ServiceContract]
public interface ISagePart
{
[OperationContract]
string SageInsertionProcess(string SQLConnectionString, string CountryCode);
// TODO: Add your service operations here
}
public class SagePartInsertion : ISagePart
{
public string SageInsertionProcess(string SQLConnectionString, string CountryCode)
{
}
}
}
here i am giving the code by which i am trying to run from win service
namespace SageDataImportWCF
{
public partial class SageDateInsertionService : ServiceBase
{
#region Local Variables
ServiceHost serviceHost;
#endregion
#region Constructor
public SageDateInsertionService()
{
InitializeComponent();
serviceHost = null;
ServiceName = "Sage DataInsertion Service";
}
#endregion
protected override void OnStart(string[] args)
{
string strAdrHTTP = "http://192.168.6.2:11000/SagePartInsertion";
if (serviceHost != null)
{
serviceHost.Close();
}
serviceHost = new ServiceHost(typeof(SageDataImportWCF.SagePartInsertion));
serviceHost.AddServiceEndpoint(typeof(SageDataImportWCF.ISagePart), new BasicHttpBinding(), strAdrHTTP);
ServiceMetadataBehavior behaviour = new ServiceMetadataBehavior();
behaviour.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(behaviour);
serviceHost.Open();
}
protected override void OnStop()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
}
}
here is my config entry for wcf service
<configuration>
<system.serviceModel>
<services>
<service name="SageDataImportWCF.SagePartInsertion" behaviorConfiguration="SageBehavior">
<endpoint address="http://localhost:9001/SagePartInsertion" contract="SageDataImportWCF.ISagePart" binding="basicHttpBinding"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="SageBehavior">
<!-- 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="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
here i have pasted all the relevant code and i like to request some one please have a look at my code and tell me why i am getting the error message like ServiceHost only supports class service types when try to run it from windows service. did i miss anything in code ?
should i have a separate project for wcf class library and another separate project for windows service because i have one project there i have files for wcf & windows service both.
so looking for suggestion like what i need to rectify in code as a result win service can start the wcf service. please help.
Check the definition of the service in the Markup:
Right click on the SagePartInsertion.svc file and select "View Markup".
Make sure the service is the implementation of the interface, like this:
<%# ServiceHost Language="C#" Debug="true" Service="SageDataImportWCF.SagePartInsertion" CodeBehind="SagePartInsertion.svc.cs" %>
In the past it failed because I was referencing the interface.

Constructor of a proxy

The solution consists of two projects:
The DemoService project, which is a simple WCF service library that implements the IGetHeaders interface. This interface consists of a single method(GetHeaders) that retrieves some information about the headers in the message sent to the service. For this exercise, it returns the Action header.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Channels;
namespace DemoService
{
public class HeaderService : IGetHeaders
{
public string GetHeaders()
{
return OperationContext.Current.RequestContext.RequestMessage.Headers.Action;
}
}
}
The TestClient project, which is a console application that enables you to consume the DemoService service. A proxy to the DemoService has already been created.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestClient
{
class Program
{
static void Main(string[] args)
{
DemoService.GetHeadersClient proxy = new DemoService.GetHeadersClient("TcpIGetHeaders");
Console.WriteLine("And the header is: " + proxy.GetHeaders());
Console.ReadLine();
}
}
}
In the constructor for the object, pass the name of the binding to use as the sole parameter.
The app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WsIGetHeaders" />
</wsHttpBinding>
<netTcpBinding>
<binding name="TcpIGetHeaders" />
</netTcpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8731/Design_Time_Addresses/DemoService/HeaderService/"
binding="wsHttpBinding" bindingConfiguration="WsIGetHeaders"
contract="DemoService.IGetHeaders" name="WsIGetHeaders">
</endpoint>
<endpoint address="net.tcp://localhost:8731/Design_Time_Addresses/DemoService/HeaderService/"
binding="netTcpBinding" bindingConfiguration="TcpIGetHeaders"
contract="DemoService.IGetHeaders" name="TcpIGetHeaders">
</endpoint>
</client>
</system.serviceModel>
</configuration>
My two questions:
In the service code, there is no constructor. Why in the proxy object, we can pass a sole parameter.
Why the parameter is the name must be the name of the endpoint, here it is ="TcpIGetHeaders".
The service does have a constructor - since one is not explicitly defined, a default parameterless constructor is supplied by the compiler. The following line of code will create a new instance of the service, even though there is no explicit constructor defined in it:
HeaderService myService = new HeaderService();
The proxy object is not creating an instance of the service - it's creating an object that can communicate with the service. When you add a service reference, .NET generates the code to create the proxy, as well as the call the methods exposed by the service.
If you look in the reference.cs file, you'll see the auto-generated code for the proxy. This proxy inherits from ClientBase<T> and implements the interface that defines your service.
DemoService.GetHeadersClient proxy = new DemoService.GetHeadersClient("TcpIGetHeaders");
The above code is calling the auto-generated GetHeadersClient class constructor, not your service constructor. The constructor for ClientBase<T> has several overloads - in the case of the code above, it's using the constructor that takes the specified endpoint configuration (determined by the name attribute on the endpoint element in the config file).
If you open the refernce.cs file, you'll probably see code similar to this (using an older example so the version numbers are probably different in your case, and I'm making an educated guess on the namespaces):
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class HeaderServiceClient : System.ServiceModel.ClientBase<TestService.DemoService.IGetHeaders>, TestService.DemoService.IGetHeaders
{
public HeaderServiceClient()
{
}
public HeaderServiceClient(string endpointConfigurationName) :
base(endpointConfigurationName)
{
}
public HeaderServiceClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{
}
public HeaderServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{
}
public HeaderServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress)
{
}
public string GetHeadesr()
{
return base.Channel.GetData(value);
}
}
Notice how the constructors that have parameters reference the base constructor from ClientBase<T>.
In summary, you're calling the constructor for the proxy, and you're using the overload that takes a string for the endpoint configuration.
See ClientBase(T Channel) Constructor for more information.

FaultException is not working correct when using BasicHttpBinding

So, I noticed FaultException is not giving me the proper result when I use the BasicHttpBinding. When I use WSHttpBinding it works file.
The issue is, From WCF Service if I throw the FaultException like below,
var translations = new List<FaultReasonText> { new FaultReasonText("FaultReasonText 1"), new FaultReasonText("FaultReasonText 2") };
throw new FaultException<MessageServiceFault>(MessageServiceFault.Fault1, new FaultReason(translations));
When it reaches to the client the fault.Reason.Translations count is 1. That means the first one (FaultReasonText 1) only is getting back to client.
But when I use WSHttpBinding the count is 2. Where the issue is? Can anyone help me on this.
It gives me different result when I test the below code with BasicHttpBinding & WSHttpBinding bindings.
class Program
{
static void Main(string[] args)
{
try
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(MessageService), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(IMessageService), new WSHttpBinding(), "");
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<IMessageService> myChannelFactory = new ChannelFactory<IMessageService>(new WSHttpBinding(), new EndpointAddress(baseAddress));
IMessageService channel = myChannelFactory.CreateChannel();
var response = channel.GetMessage();
}
catch (FaultException fault)
{
fault.Reason.Translations.ToList().ForEach(i => Console.WriteLine(i.Text));
Console.WriteLine(false);
}
}
}
[ServiceContract]
public interface IMessageService
{
[OperationContract]
[FaultContract(typeof(MessageServiceFault))]
string GetMessage();
}
public class MessageService : IMessageService
{
public string GetMessage()
{
var translations = new List<FaultReasonText> { new FaultReasonText("FaultReasonText 1"), new FaultReasonText("FaultReasonText 2") };
throw new FaultException<MessageServiceFault>(MessageServiceFault.Fault1, new FaultReason(translations));
}
}
[DataContract]
public enum MessageServiceFault
{
[EnumMember]
Fault1,
[EnumMember]
Fault2
}
EDIT:
But, this article says, You can supply a number of different text strings that get picked from depending on the user's language settings. The Translations bucket holds all of the different text strings and their associated cultural identifiers (tied together by a FaultReasonText). When no culture is specified for a fault reason or a translation search, the assumed culture is the current thread culture. For example, if you want a translation to "en-UK", we'll first look for "en-UK" and then we'll look for "en". If we still can't find a match, then we'll take the first translation in the list, which could be anything.
If so, Why in case of WsHttpBinding it returns me the 2 FaultReasonText ?
To use FaultException, you need to activate SOAP 1.2 on your web service.
BasicHttpBinding uses SOAP 1.1, WSHttpBinding uses SOAP 1.2. That's why it works with WSHttpBinding and not with BasicHttpBinding.
Instead of using BasicHttpBinding, you should better use customBindings, with textMessageEncoding and httpTransport :
<customBinding>
<binding name="simpleBinding">
<textMessageEncoding messageVersion="Soap12" writeEncoding="utf-8" />
<httpTransport />
</binding>
</customBinding>
If you convert a default basicHttpBinding with this tool : you will obtain :
<!-- generated via Yaron Naveh's http://webservices20.blogspot.com/ -->
<customBinding>
<binding name="NewBinding0">
<textMessageEncoding MessageVersion="Soap11" />
<httpTransport />
</binding>
</customBinding>
<!-- generated via Yaron Naveh's http://webservices20.blogspot.com/ -->
Source binding :
<bindings>
<basicHttpBinding>
<binding name="NewBinding0" />
</basicHttpBinding>
</bindings>
Try to activate SOAP 12 to your service, and it will work

WCF Security Using Windows Authentication

What is the correct WCF security implementation/configuration that allows:
Using existing Windows accounts to authenticate with the service
Allow adding of a Service Reference from another project without providing
credentials
Limiting the users that can call the service
Using existing Windows accounts to authenticate with the service
To do this, you should set the transport clientCredentialType attribute of the binding configuration to Windows.
<bindings>
<wsHttpBinding>
<binding>
<security mode="Message">
<transport clientCredentialType="Windows" />
</security>
</binding>
</wsHttpBinding>
</bindings>
Allow adding of a Service Reference from another project without providing credentials
To do this, create a mex endpoint for your service endpoint.
<services>
<service name="Services.SampleService" behaviorConfiguration="wsDefaultBehavior">
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
Limiting the users that can call the service
This one is a little more involved. The way I found to secure a service on a per-user basis requires a custom authorization policy. The class that performs the authorization must implement the IAuthorizationPolicy interface. This is the complete code of my authorization class:
namespace Services.SampleService.Authorization
{
/// <summary>
/// Handles the default authorization for access to the service
/// <para>Works in conjunction with the AuthorizedUsersDefault setting</para>
/// </summary>
public class DefaultAuthorization: IAuthorizationPolicy
{
string _Id;
public DefaultAuthorization()
{
this._Id = Guid.NewGuid().ToString();
}
public bool Evaluate(EvaluationContext evaluationContext, ref object state)
{
bool isAuthorized = false;
try
{
//get the identity of the authenticated user
IIdentity userIdentity = ((IIdentity)((System.Collections.Generic.List<System.Security.Principal.IIdentity>)evaluationContext.Properties["Identities"])[0]);
//verify that the user is authorized to access the service
isAuthorized = Properties.Settings.Default.AuthorizedUsersDefault.Contains(userIdentity.Name, StringComparison.OrdinalIgnoreCase);
if (isAuthorized)
{
//add the authorized identity to the current context
GenericPrincipal principal = new GenericPrincipal(userIdentity, null);
evaluationContext.Properties["Principal"] = principal;
}
}
catch (Exception e)
{
Logging.Log(Severity.Error, "There was an error authorizing a user", e);
isAuthorized = false;
}
return isAuthorized;
}
public ClaimSet Issuer
{
get { return ClaimSet.System; }
}
public string Id
{
get { return this._Id; }
}
}
}
The "magic" happens in the Evaluate method. In my case, the list of authorized users is maintained in a Properties.Settings variable (of type ArrayOfString) named AuthorizedUsersDefault. This way, I can maintain the user list without having to redeploy the entire project.
And then, to use this authorization policy on a per-service basis, set the following in the ServiceBehaviors node:
<behaviors>
<serviceBehaviors>
<behavior name="wsDefaultBehavior">
<serviceAuthorization principalPermissionMode="Custom">
<authorizationPolicies>
<add policyType="Services.SampleService.Authorization.DefaultAuthorization, MyAssemblyName" />
</authorizationPolicies>
</serviceAuthorization>
</behavior>
</serviceBehaviors>
</behaviors>

WCF - IErrorHandler vs Authentication

I'm writing a WCF service with some authentication and a custom error handler. However, I'm coming up against this problem: my implementation of IErrorHandler is not getting hit when the authentication throws an exception, but runs just fine with other exeptions.
Does authentication run before IErrorHandler gets built? Am I barking up the wrong tree trying to get it to catch those errors?
Yes, I have tried (and am) throwing a FaultException in my authentication, not SecurityTokenException.
So first thing is to make sure that your custom Error Handler is also implementing IServiceBehavior. IServiceBehavior requires that you implement a couple other methods but the important one is "ApplyDispatchBehavior", in which you must add the ErrorHandler to the channel dispatchers.
C#
public class CustomErrorHandler: IServiceBehavior, IErrorHandler
{
public bool HandleError(Exception error)
{
//Return True here if you want the service to continue on as if
// the error was handled
return true;
}
public void ProvideFault(Exception error,
MessageVersion version,
ref Message fault)
{
FaultException fe = new FaultException(
new FaultReason(error.Message),
new FaultCode("Service Error"));
MessageFault mf = fe.CreateMessageFault();
fault = Message.CreateMessage(version, mf, fe.Action);
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase)
{
IErrorHandler eh = new CustomErrorHandler();
foreach (ChannelDsipatcherBase cdb in serviceHostBase.ChannelDispatchers)
{
ChannelDispatcher cd = cdb as ChannelDispatcher;
cd.ErrorHandlers.Add(eh);
}
}
public void AddBindingParameters(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase,
Collection<ServiceEndpoint> endpoints,
BindingParameterCollection bindingParameters)
{
//Add binding parameters if you want, I am not
}
public void Validate(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase)
{
//Add custom fault validation here if you want
}
}
Then you need to add the CustomErrorHandler as a service behavior and add the behavior
web.config
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="ErrorHandler"
type="ServiceNamespace.CustomErrorHandler, ServiceNamespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>
<behaviors>
<serviceBehaviors>
<behavior name="MyBehavior1">
<!--Put other behaviors for your service here then add the next line-->
<ErrorHandler />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
This way all your thrown exceptions will be converted to faults to return back to the client.
In the case of SecurityTokenExceptions, you do not want to convert those to Fault Exceptions right away. You actually do want to throw these as SecurityTokenExceptions in the custom validation in order for the service/server to recognize that the security authorization failed, and automatically returns as a fault equiv of a "403 : Access Denied". I am not 100% but I think that the custom auth and validation pieces happen before custom service behaviors, like the error handler, are loaded. Unfortunately, if you need to troubleshoot something in your auth, you will need to turn on WCF tracing on the service, see this article titled "How to turn on WCF Tracing".
If you need to log failed auth attempts, you will probably need to put it directly in your custom validator.