[WCF] Testing Message and Method Security with Windows

While digging a bit deeper into Message and Method Security options for WCF services, I ran upon several good articles by Michèle Leroux Bustamante, both on TheServerSide.NET and on the That Indigo Girl blog she created for her book, "Learning WCF". I've just ordered the book and cannot wait to get my hands on it. I read several of the preview chapters she published on her blog and I really like the way she explains things. Good stuff, go get the book already!

So I can't take credit for any of the code in this blog post, I'm just putting things up here for myself for safe keeping and for others to learn. The documentation and samples around message security on MSDN is also pretty good, for example - http://msdn.microsoft.com/en-us/library/ms730301.aspx

So, this is a sample to do message security with a Windows client. It also shows how to make sure the caller belongs to a certain group or role to access it.

SERVICE CODE

So, to make sure the caller is a member of the Administrators group, you decorate the method with a PrincipalPermission attribute like this:

[ServiceContract()]

public interface IMyService

{

[OperationContract]

string MyOperation1(string myValue1);

}

public class MyService : IMyService

{

[PrincipalPermission(SecurityAction.Demand, Role = "Administrators")]

public string MyOperation1(string myValue1)

{

/// do something...

}

}

SERVICE CONFIGURATION

The service configuration needs to declare that message security should be handled by Windows.

<system.serviceModel>

<services>

<service name="MyService" >

<endpoint contract="IMyService" bindingConfiguration="wsHttpWindows" binding="wsHttpBinding"/>

</service>

</services>

<bindings>

<wsHttpBinding>

<binding name = "wsHttpWindows">

<security mode="Message">

<message clientCredentialType="Windows" />

</security>

</binding>

</wsHttpBinding>

</bindings>

</system.serviceModel>

CLIENT CODE

You don't need to do anything special for the client code part. Just make the call. The config file needs to be edited though.

CLIENT CONFIGURATION

Likewise, the client needs to declare the equivalent security means in its configuration file:

<system.serviceModel>

<bindings>

<wsHttpBinding>

<binding name="WSHttpBinding_IMyService" >

<security mode="Message">

<message clientCredentialType="Windows" />

</security>

</binding>

</wsHttpBinding>

</bindings>

<client>

<endpoint address="http://localhost:1035/MessageSecurityWindows/Service.svc"

binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IMyService"

contract="MessageSecurityWindowsClient.MyService.IMyService"

name="WSHttpBinding_IMyService">

</endpoint>

</client>

</system.serviceModel>

It's all created for you if you "Add Service Reference", which of course requires you to first add an "mex" endpoint to the service.

No Comments