Zulfiqar's weblog

WCF/WF/AppFabric & random .Net stuff

  • Note: I recently moved my blog so some of the links might be broken. If you can’t find what you are looking for or getting a “404 - Not Found” error, please try blog search.

  • CONTACT

Deploying Umbraco to Windows Azure

Posted by zamd on January 27, 2012

Umbraco is a fairly mature CMS system and recently I was engaged in an assignment to deploy Umbraco CMS to Windows Azure. In this post, I’ll share some of my learning’s.

  • Umbraco accelerator (I call it bootstrapper) works well for small to medium web sites but you definitely have to increase the default blob sync interval which by default is set to 1 second.
  • In the context of Windows Azure, accelerator/bootstrapper become your main application which gets deployed to Azure Web Roles using Azure service model.
  • Umbraco installation (I used standard Umbraco download) is stored in blob storage while accelerator is configured to pick this and install it on the web roles where accelerator itself is running. Accelerator does both push & pull so file system changes done by Umbraco would be pushed to blob storage and automatically be synced to other web roles by the accelerator.
  • The standard Azure staging/production deployment doesn’t really fit with accelerator style deployment used by Umbraco. So instead of using staging & production, we used azure production environment only(with well known DNS) and decided to use two hosted services representing UAT & Live environments. Our plan is to use end to end separation i.e. separate blob storage & separate SQL Azure databases. This setup would give us required change management & content management control.
  • Using accelerator I was quickly able to deploy Umbraco web app to two Azure web roles.
  • Soon after the deployment I was welcomed by ASP.net yellow screen of death.
  • I RDP into the server and debugged the W3P.exe to realize ASP.net was failing to validate ViewState.  Make sense! :) Azure is load-balanced & requests were sent to two web role instances in a round robin scheme. ASP.net machine key scheme was set to default Autogenerate which resulted in both web roles using different keys to secure/validate ViewState. Once we knew the issue the fix was simple:
  • Use pre-generated fixed key values for <machineKey>
<machineKey validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7"
            decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
            validation="SHA1"
            decryption="AES"/>
  • Next step was to create the Umbraco database for which we decided to use SQL Azure as the DB platform.
  • My first thoughts were to use the basic approach of manually creating a blank DB in Sql Azure and then run Umbraco configuration wizard to populate the schema & data. Even though this approach won’t give us necessary control for the DB assets it was simple to use.
  • Turns out this approach doesn’t work & Umbraco simply hangs. I debugged & found Umbraco configuration wizard was unable to create couple of columns (of bit data type) & data access was failing because of the missing columns. I discarded this approach without going any further.
  • I then installed a local Umbraco instance and configured a local Sql Server database which worked smoothly.
  • I used data tier application framework to export local SQL Server database as a package. As SQL Azure natively supports import of dacpac packages, the import was fairly simple process using the Sql Azure management portal.
  • The dacpac approach also solved the lack of control issues with the simple in-place DB creation option as it gave us a golden copy of the database for future use. We are also planning to use dacpac feature as the basis for backup & restore requirements.
  • Once DB is ready in SQL Azure,  Umbraco was configured to use this DB and we have a somewhat working Umbraco installation.
  • During testing, I quickly realized that by default Umbraco stores session state in memory and this would not work in Window Azure load balanced environment.
  • I could use SQL Azure for session state storage but it’s NOT supported in SQL Azure and also adds quite a bit of overhead in terms of session state clean up as there is no SQL Agent in Azure.
  • I decided to use Windows Azure Cache (a.k.a AppFabric cache) as the session state storage mechanism. It’s fast & also doesn’t require additional data purge solutions. I created a 128MB cache and configured Umbaco web app to use AppFabric cache (instead of local machine’s memory) as the session state storage.
  • And finally Umbraco is up & running in Azure :)

Enjoy…

Posted in Windows Azure | Leave a Comment »

WebSockets with WCF

Posted by zamd on November 23, 2011

Notification & “Duplex communication” are important scenario over the internet but firewalls and browser limitations makes them very hard to implement. In the browser world, tricks like long polling is commonly used to implement server-push requirements. For non-browser scenarios relay technologies like Azure Service Bus overcome the lack of inbound connectivity by creating a relay in the cloud where both client & server connects by making an outbound connection. Both long polling & relay works but are not optimum solutions due to latency and the complexity involved.

WebSockets is designed to address some of these limitation. With WebSockets, a client & server can upgrade an existing HTTP connection to a full-duplex TCP/IP connection or setup a new WebSockets connection using an HTTP based handshake. WebSockets uses standard HTTP ports (80, 443) so it’s just works with Firewall & the existing security infrastructure. WebSockets technology bucket has following two parts:

  1. WebSockets Protocol  (Currently being standardized by IETF)
  2. WebSockets JavaScript API (Currently being standardized by W3C)

Windows “8” has native support for WebSockets protocol & there are quite a few API (native & managed) available for programing WebSockets servers & clients on windows. In addition, IE 10 supports both Web Sockets protocol & the JavaScript API.

Client:

  • IE 10
  • WinRT

Server:

  • Native windows implementation ( >= Windows “8”)
    • IIS 8.0
  • System.Net.WebSockets (Managed Wrapper)
    • HttpListener
  • System.Web (ASP.net)
    • HttpContext
  • System.ServiceModel (WCF)
    • NetHttpBinding

WCF supported duplex services since V1 but these required either a duplex transport binding (netTcpBinding, netNamedPipeBinding) or wsDualHttpBinding which forces a client to have a public URI accessible to service (and to the world Smile)   running on the public internet.

wsDualHttpBinding is not really suitable for internet scenarios due to inbound connectivity issues. NetTcpBinding could also be problematic in tightly-locked down environments allowing only outbound connections to port 80/443.

With the WebSockets support in Windows, WCF introduced a new Binding NetHttpBinding which does binary SOAP messaging over WebSockets protocol and overcome the limitations of existing bindings. Below I created a basic duplex WCF service

Basic Service
[ServiceContract(CallbackContract=typeof(IPing))]
public interface IPing
{
    [OperationContract(IsOneWay=true)]
    void Ping(string msg);
}

class PingService : IPing
{
    public void Ping(string msg)
    {
        Console.WriteLine("Service: {0}",msg);
        var chnl = OperationContext.Current.GetCallbackChannel<IPing>();

        chnl.Ping(string.Format("You said \"{0}\"?", msg));
    }
}

Standard WCF hosting code with one endpoint using the new binding (line 5 & 14)

Hosting
  1. static void Main(string[] args)
  2. {
  3.     var sh = new ServiceHost(typeof(PingService),
  4.         new Uri("http://localhost:9090/"));
  5.     var binding = new NetHttpBinding();
  6.     sh.AddServiceEndpoint(typeof(IPing), binding, "Ping");
  7.  
  8.     sh.Open();
  9.  
  10.     Console.WriteLine("Service ready…");
  11.  
  12.     var cf = new DuplexChannelFactory<IPing>(
  13.         new InstanceContext(new PingBack()),
  14.         binding,
  15.         new EndpointAddress("http://localhost:8080/Ping"));
  16.  
  17.     var chnl = cf.CreateChannel();
  18.     chnl.Ping("Hello!");
  19.  
  20.     Console.WriteLine("Finishing…");
  21.     Console.ReadLine();
  22. }

and finally my callback handler class.

Callback handler
public class PingBack : IPing
{
    public void Ping(string msg)
    {
        Console.WriteLine("Client: {0}",msg);
    }
}

Running the project I get the expected output.

By default, WebSockets protocol is allowed on NetHttpBinding i.e. if your contract is a Duplex contract NetHttpBinding automatically upgrades to WebSockets protocol. Out of box, this binding does SOAP messaging and encodes SOAP using the WCF binary encoding. You can reuse the WebSockets transport binding element in a custom binding to support other encodings & protocols and I’ll talk about this in a future post.

image

Posted in Uncategorized | Leave a Comment »

Pub/Sub with WCF (Part 2)

Posted by zamd on May 25, 2011

Source Code Download

Service Bus May CTP has a small glitch when it comes to pub/sub messaging using the WCF programing model. The May CTP API out-of-box doesn’t pick up filter/promoted properties from the WCF data contracts and requires you to explicitly specify these properties on the BrokeredMessage object outside of core WCF programing model as shown in part 1.

I didn’t like this repetition and decided to prototype a solution using the WCF extensibility model and after few hours of coding created a solution which looks quite cool :)

In my solution a DataMember can be marked with [PromotedProperty] attribute and a custom operation behavior picks these annotations and promote them as filter properties by automatically attaching them with the outgoing message.

    public class Order
    {
public double Amount { get; set
; }
[PromotedProperty]
        public string ShipCity { get; set
; }
}

[ServiceContract]
public interface IOrderService
    {
[
OperationContract(Name = "SubmitFlat", IsOneWay = true
)]
[PropertyPromotionBehavior]
        void Submit(double amount, [PromotedProperty] string
shipCity);

[OperationContract(IsOneWay = true)]
[
PropertyPromotionBehavior
]
void Submit(Order order);
}

I have decided to use a custom formatter to implement property lifting and injection functionality primarily because at the formatter level I still have a fairly typed view of the method call. At message inspector level most of typed-ness has gone and it would have required more work.

The [PropertyPromotionBehavior] creates a ‘promotion model’ (list of properties needs to be promoted) by reflecting on the data contract. The ‘promotion model’ is then populated by the custom formatter with actual parameter values extracted from the call context. [PropertyPromotionBehavior] also replaces the default formatter with a custom PromotionFormatter which wraps the default formatter and does the additional work of property promotion. I have highlighted the relevant bits below.

    [AttributeUsage(AttributeTargets.Method)]

    publicclassPropertyPromotionBehaviorAttribute : Attribute, IOperationBehavior

    {

        publicvoid Validate(OperationDescription operationDescription) { }

 

        publicvoid ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) { }

 

        publicvoid ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)

        {

            var promotedProperties = LoadPromotedProperties(operationDescription);

            if (promotedProperties.Count <= 0) return;

 

            var dummy = newClientOperation(clientOperation.Parent, “dummy”, “urn:dummy”);

            var behavior =

                operationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>() asIOperationBehavior;

            behavior.ApplyClientBehavior(operationDescription, dummy);

 

            clientOperation.Formatter = newPromotionFormatter(dummy.Formatter, promotedProperties);

            clientOperation.SerializeRequest = dummy.SerializeRequest;

        }

 

        publicvoid AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) { }

 

       …

    }

    classPromotionFormatter : IClientMessageFormatter

    {

        privatereadonlyIClientMessageFormatter _orignalFormatter;

        privatereadonlyIList<PromotedPropertyDescription> _promotions;

 

        public PromotionFormatter(IClientMessageFormatter orignalFormatter, IList<PromotedPropertyDescription> promotions)

        {

            _orignalFormatter = orignalFormatter;

            _promotions = promotions;

        }

 

        publicobject DeserializeReply(Message message, object[] parameters)

        {

            return _orignalFormatter.DeserializeReply(message, parameters);

        }

 

        publicMessage SerializeRequest(MessageVersion messageVersion, object[] parameters)

        {

            var message = _orignalFormatter.SerializeRequest(messageVersion, parameters);

 

 

            if (_promotions.Count > 0)

            {

                var bmp = newBrokeredMessageProperty();

                foreach (var promotion in _promotions)

                {

                    bmp.Properties[promotion.Name] = promotion.Value;

                }

                message.Properties[BrokeredMessageProperty.Name] = bmp;

            }

                                                              

            return message;

        }

    }

With these extensions in place, the code looks just like the normal WCF code and property promotion happens in the background as you would expect.

var cf = new ChannelFactory<IOrderService>(serviceBusBinding, topicAddress); 
var proxy = cf.CreateChannel();

proxy.Submit(new Order { Amount = 200, ShipCity = “london” });

proxy.Submit(new Order { Amount = 322, ShipCity = “reading” });

proxy.Submit(101, “reading”);

Console.WriteLine(“Submitted.”);

Hopefully Service Bus programing model will support this kind of behavior soon but for the time being these extensions would probably fill the gap.

I have attached complete source code with this post so please feel free to download and use.

Posted in ServiceBusV2 | 1 Comment »

Pub/Sub with WCF (Part 1)

Posted by zamd on May 19, 2011

Code download

In yesterday’s post I have explored how to use Service Bus queues as a transport to communicate between a WCF client and a service. In today’s post I will show you WCF pub/sub messaging using the topics and subscriptions. A subscription behaves exactly like a queue for reads while a topic behaves exactly like a queue for writes. This metaphor maps nicely to WCF where our services would listen on different subscriptions while the clients would send messages to a single topic. Service Bus would automatically forward matching messages to correct services.

For this example, I have created a simple order service as shown below. The Write extension simply writes to the console using a certain color assigned to a particular host. I have used this to distinguish the service host receiving the messages.

public class Order
{
    public double Amount { get; set; }
    public string ShipCity { get; set; }
}

[ServiceContract]
public interface IOrderService
{
    [OperationContract(IsOneWay = true)]
    void Submit(Order order);
}

public class OrderService : IOrderService
{
    public void Submit(Order order)
    {
        var writer = OperationContext.Current.Host.Extensions.Find<Writer>();

        writer.WriteLine("Received order value = {0}, ShipCity = {1}", order.Amount, order.ShipCity);
    }
}

Next I use the Management API to create topics & related subscriptions.

var baseAddress = "sb://soundbyte.servicebus.appfabriclabs.com";
var credential = TransportClientCredentialBase.CreateSharedSecretCredential("owner", "zYDbQ2wM4343dbBukWJTF6Y=");
var namespaceClient = new ServiceBusNamespaceClient(baseAddress, credential);

try
{
    namespaceClient.DeleteTopic("orders");
}
catch { }

var topic= namespaceClient.CreateTopic("orders");
topic.AddSubscription("london", new SqlFilterExpression("ShipCity = 'london'"));
topic.AddSubscription("reading", new SqlFilterExpression("ShipCity = 'reading'"));

Both subscriptions has a filter applied to them and only the messages matching this filter would be delivered to the subscription. I then create two separate service hosts simulating separate services running in different cities. I assigned ‘Cyan’ color to the London host (simulated service hosted in London) and ‘Yellow’ to the Reading Host (Service hosted in Reading).

var serviceBusBinding = new ServiceBusMessagingBinding();
serviceBusBinding.MessagingFactorySettings.Credential = credential;

string topicAddress = baseAddress + "/orders";
string londonSubscription = baseAddress + "/orders/subscriptions/london";
string readingSubscription = baseAddress + "/orders/subscriptions/reading";

var hostLondon = new ServiceHost(typeof(OrderService));
hostLondon.Extensions.Add(new Writer(ConsoleColor.Cyan));
hostLondon.AddServiceEndpoint(typeof(IOrderService), serviceBusBinding, new Uri(topicAddress), new Uri(londonSubscription));
hostLondon.Open();

var hostReading = new ServiceHost(typeof(OrderService));
hostReading.Extensions.Add(new Writer(ConsoleColor.Yellow));
hostReading.AddServiceEndpoint(typeof(IOrderService), serviceBusBinding, new Uri(topicAddress), new Uri(readingSubscription));
hostReading.Open();

Next I have created a simple WCF client using the ChannelFactory API and used it to send messages to the topic. In the current CTP, you have to set the filter properties separately on the BrokeredMessage object, which is a native ServiceBus message object and is different from the WCF Message object.

ServiceBusMessagingBinding automatically converts the WCF message object (generated by the proxy object) to a BrokeredMessage object which is then sent to ServiceBus. On the receive side a similar conversion happens from BrokeredMessage to a WCF Message which is then on to WCF Service. To set BrokeredMessage specific properties, we need to create a BrokeredMessageProperty object, set the properties on it and add it to generated WCF messages. ServiceBusMessagingBinding looks for this property and copy all the properties to the BrokeredMessage object it creates. I’m doing exactly the same using the OperationContextScope below.

var cf = new ChannelFactory<IOrderService>(serviceBusBinding, topicAddress);
var proxy = cf.CreateChannel();

using (new OperationContextScope( (IContextChannel)  proxy))
{
    var bmp = new BrokeredMessageProperty();
    bmp.Properties["ShipCity"] = "london";
    OperationContext.Current.OutgoingMessageProperties.Add(BrokeredMessageProperty.Name, bmp);
    proxy.Submit(new Order {Amount = 200, ShipCity = "london"});

    bmp.Properties["ShipCity"] = "reading";
    proxy.Submit(new Order { Amount = 322, ShipCity = "london" });

}

As you can see from the following output that the ‘london’ message was received by London host (‘yellow’) while the ‘reading’ message was received by Reading (‘cyan’) service host.

image

Finally yes it looks bit ugly that I have to specify these promoted/filter properties separately Sad smilefrom their WCF contract values. Ideally ServiceBus APIs should have picked up the ShipCity property from my Order object.  Unfortunately in the current CTP you have to do this separately as I have shown you in the above snippet.  In the next post I’ll show how you can extend WCF so that it automatically picks these ‘filter properties’  from operations parameters or WCF DataContract(s).

Stay tuned…

Posted in ServiceBusV2 | 3 Comments »

WCF with Service Bus V2: Queues

Posted by zamd on May 18, 2011

May CTP of Service Bus introduced tons of new messaging capabilities including Queuing and Topic based pub/sub messaging. Check out Clemens post for an overview.

The usage of Service Bus messaging entities (Queues, Topics) is divided across two namespaces – a ‘Management Namespace’ and a ‘Runtime Namespace’. Management namespace is used to create/define messaging entities while the Runtime Namespace is used to do the actual messaging operations using the already defined ‘messaging entities’. The management namespace is exposed using as a REST service and Service Bus SDK also provides with a client library which hides the HTTP based interface behind a nice object oriented API.

So once a messaging entity (for example a Queue) is created and is ready you can use the Runtime API to send/receive messages. May CTP comes with two flavours of runtime APIs.

  • A low level MessagingFactory based API: Which is the native, high fidelity Service Bus API exposing all the Service Bus messaging features.
  • A higher level WCF binding: Which internally uses the MessagingFactory API and integrates the Service Bus messaging with WCF programing model.

There are already few blogs posts which talks about the MessagingFactory API so I’m not going to repeat that here. Let’s see how can I use Service Bus queues a communication mechanism between my WCF client & service. I’ll start with creating a usual one-way service as you would do for MSMQ or any other queuing technology.

    [ServiceContract]
    public interface IHelloService
    {
        [OperationContract(IsOneWay = true)]
        void SayHello(string input);
    }

    public class HelloService : IHelloService
    {
        public void SayHello(string input)
        {
            Console.WriteLine("Says: " + input);
        }
    }

 

Following snippet create a queue (line 6) using the management API. I’m using the wrapper class provided with the SDK for the REST based management service.

I then create a binding instance and specify ACS credentials on it. All the operations on Service Bus requires a valid token from ACS and these credentials would be used to acquire an ACS token for SB operations.

Finally I added an endpoint specifying the queue location as the endpoint address.

  1. static void Main(string[] args)
  2. {
  3.     const string baseAddress = "sb://soundbyte.servicebus.appfabriclabs.com";
  4.     var credential = TransportClientCredentialBase.CreateSharedSecretCredential("owner",
  5.                                                                                 "zYDbQ2wM1k7J32323232323VdbBukWJTF6Y=");
  6.     CreateQueue(baseAddress, credential,"q1");
  7.  
  8.     var serviceBusBinding = new ServiceBusMessagingBinding();
  9.     serviceBusBinding.MessagingFactorySettings.Credential = credential;
  10.  
  11.     var sh = new ServiceHost(typeof (HelloService));
  12.     sh.AddServiceEndpoint(typeof (IHelloService), serviceBusBinding, baseAddress + "/q1");
  13.     sh.Open();
  14.  
  15.  
  16.  
  17.     Console.WriteLine("Host ready…");
  18.  
  19.     var cf = new ChannelFactory<IHelloService>(serviceBusBinding, baseAddress + "/q1");
  20.     var proxy = cf.CreateChannel();
  21.     for (int i = 0; i < 10; i++)
  22.     {
  23.         proxy.SayHello("Hi " + i);
  24.     }
  25.  
  26.     Console.ReadLine();
  27. }

 

My client is a standard WCF proxy (line 19-23) which is sending messages to the same endpoint address (queue location) using the same ServiceBus binding.

The above produces following expected output. Easy isn’t it?

image

By integrating Service Bus messaging with WCF programing model, we can reuse all of the WCF goodness with Service bus messaging. For example I can secure messages while they are traveling through queues/topics by just changing the binding.

Next time I’ll show how to do pub/sub using the WCF programing model.

Posted in ServiceBusV2 | 2 Comments »

NuGet Package to enable SWT in WIF

Posted by zamd on April 27, 2011

Just found Daniel Cazzulino@Clarius has packaged some of my work in a reusable NuGet package. Pretty cool…

image

http://nuget.org/List/Packages/netfx-Microsoft.IdentityModel.Swt

Posted in WIF | Leave a Comment »

Silverlight Claim-Based-Security Part-2

Posted by zamd on March 23, 2011

In part 1 I talked about a simple approach to combine WCF Routing service and claims-based security and I got some questions about the sample code and routing service configuration. In this post, I’ll explain some additional scenarios and would provide link to the source code. In my original post I used following very simple routing configuration where the RST (Request Security Token) message goes to the STS and everything else goes to the UserService (a business service)

Simple Routing Configuration
  1. <routing>
  2.   <filterTables>
  3.     <filterTable name="SLRouting">
  4.       <add endpointName="stsEndpoint" filterName="matchRST" priority="5"/>
  5.       <add endpointName="serviceEndpoint" filterName="allMessages" priority="1"/>
  6.     </filterTable>
  7.   </filterTables>
  8.   <filters>
  9.     <filter filterType="Action" filterData="http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue" name="matchRST"/>
  10.     <filter filterType="MatchAll" name="allMessages"/>
  11.   </filters>
  12. </routing>

 

The STS endpoint uses an action filter (line 4) which looks for a WS-Trust RST message and forwards it to the STS. If RST filter doesn’t match, then the routing engine goes and tries the second filter (line 5) which is a match all. So in my simple configuration all non-RST messages are simply sent to the second endpoint. Real world scenarios obviously would require more granular routing but it can easily be enabled using the same pattern. WCF routing configuration is quite powerful and supports composite (AND, OR etc) and custom filters using which you can model any routing logic as you per your needs.

Another interesting scenarios is to support multiple authentication schemes on the STS – windows authentication for the intranet while userName password for the internet. 

To enables this I have exposed the STS functionality using two different endpoints supporting both username/password based authentication as well as windows authentication. 

/ActiveSTS/issue.svc/IWSTrust13/ActiveSTS/windowsintegrated/issue.svc/IWSTrust13

Because windows authentication is point-point so I relied on impersonation to flow the end-user identity to the STS via the Router. The windows authentication flow looks like this:

image

For the windows-integrated endpoint,  router is configured to impersonate the client and the outgoing messages is sent under this impersonated context which enables the STS to authenticate the original user using windows authentication.

      <serviceBehaviors>        <behavior>          <serviceAuthorization impersonateCallerForAllOperations="true"/>                  </behavior>      </serviceBehaviors>

When deploying in IIS, both the router endpoint and the STS endpoint needs to be configured for windows-authentication and I have accomplished it by creating a sub-folder (windowsintegrated) under both virtual directories and configuring this for windows-authentication. The main/parent virtual directories still has anonymous access enabled for the userName authentication to work. Note with userName authentication,  the credentials goes inside the SOAP message. My VS setup look like this:

image

The web.config(s) under the ‘windowsintegrated’ folder overrides the settings to enable windows-authentication. For example, in the STS project the root web.config defines both service endpoints along with a default binding which is configured for UserName authentication over HTTP.

Root web.config: STS
  1. <system.serviceModel>
  2.   <serviceHostingEnvironment>
  3.     <serviceActivations>
  4.       <add relativeAddress="~/issue.svc" service="CustomSecurityTokenServiceConfiguration"
  5.            factory="Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceHostFactory"/>
  6.       
  7.       <add relativeAddress="~/windowsintegrated/issue.svc" service="CustomSecurityTokenServiceConfiguration"
  8.            factory="Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceHostFactory"/>
  9.     </serviceActivations>
  10.   </serviceHostingEnvironment>
  11.  
  12.   <services>
  13.     <service name="Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceContract">
  14.       <endpoint address="IWSTrust13"
  15.                 binding="customBinding"
  16.                 contract="Microsoft.IdentityModel.Protocols.WSTrust.IWSTrust13SyncContract"/>
  17.     </service>
  18.   </services>
  19.  
  20.   <bindings>
  21.     <customBinding>
  22.       <binding>
  23.         <security authenticationMode="UserNameOverTransport" allowInsecureTransport="true"/>
  24.         <httpTransport/>
  25.       </binding>
  26.     </customBinding>
  27.   </bindings>
  28. </system.serviceModel>

 

The web.config in the ‘windowsintegrated’ changes the default binding to enable windows authentication. I’m using the ‘Simplified WCF Configuration’ here so the final config is very clean as a result.

Overriden default CustomBindin
  1. <system.serviceModel>
  2.   <services/>
  3.   <bindings>
  4.     <customBinding>
  5.       <binding>
  6.         <httpTransport authenticationScheme="Negotiate"/>
  7.       </binding>
  8.     </customBinding>
  9.   </bindings>
  10. </system.serviceModel>

Similar technique is used on the WebSite/Router where I pick different STS endpoint/binding depending on the chosen router endpoint. The root web.config goes to the anonymous STS endpoint (line 2 & 3) and authentication is done using the message credentials (userName).

Root web.config WebSite
  1. <client>
  2.   <endpoint name="stsEndpoint" address="http://localhost/ActiveSTS/issue.svc/IWSTrust13"
  3.             binding="customBinding" bindingConfiguration="outBinding" contract="*">
  4.   </endpoint>
  5.  
  6.   <endpoint name="serviceEndpoint" address="http://localhost/UserService/Service1.svc"
  7.       binding="customBinding" bindingConfiguration="outBinding" contract="*">
  8.  
  9.   </endpoint>
  10.  
  11. </client>

 

Web.config in the ‘windowsintegrated’ changes the default STS endpoint/binding to match the windows authentication requirements and also enables impersonation to flow windows identity to the STS.

Router config for windows auth
  1. <system.serviceModel>
  2.   <services/>
  3.   <client>
  4.     <remove name="stsEndpoint"/>
  5.     <endpoint name="stsEndpoint" address="http://localhost/ActiveSTS/windowsintegrated/issue.svc/IWSTrust13"
  6.               binding="customBinding" bindingConfiguration="outBinding" contract="*"/>
  7.   </client>
  8.   <bindings>
  9.     <customBinding>
  10.       <binding name="inBinding">
  11.         <httpsTransport authenticationScheme="Negotiate"/>
  12.       </binding>
  13.  
  14.       <binding name="outBinding">
  15.         <httpTransport authenticationScheme="Negotiate"/>
  16.       </binding>
  17.  
  18.     </customBinding>
  19.   </bindings>
  20.   <behaviors>
  21.     <serviceBehaviors>
  22.       <behavior>
  23.         <serviceAuthorization impersonateCallerForAllOperations="true"/>          
  24.       </behavior>
  25.     </serviceBehaviors>
  26.   </behaviors>
  27. </system.serviceModel>

 

Finally make sure to enable integrated windows authentication on the ‘windowsintegrated’ directory in IIS before you run the samples.

image

enjoy…

Download: Sample solution

Posted in Uncategorized | Leave a Comment »

Using Simple Web Token (SWT) with WIF

Posted by zamd on February 8, 2011

SAML 1.1/SAML 2.0 is the default token format when using ACS as the authentication service for your website. In this model, your website talks to ACS using WS-Federation protocol and what it normally gets back is a Saml token. This scenarios is fairly straight-forward as WIF natively supports WS-Federation protocol & SAML1.1/SAML 2.0 token formats.

There are cases where you might want to return a Simple Web Tokens (SWT) after a successful authentication. For example, you might want to use this same SWT (available as a bootstrap token) to call other downstream REST/OData services as depicted in the following diagram.

image

ACS fully supports returning an SWT token after a successfully WS-Fed authentication but WIF currently doesn’t support SWT tokens. You would have to write a custom Security Token Handler for WIF to process SWT tokens coming back to your website. I have created some extensions which enables this and other OAuth WRAP related scenarios. Feel free to download the code from my SkyDrive.

Posted in WIF, Windows Azure AppFabric | 8 Comments »

Silverlight Claim-Based-Security

Posted by zamd on February 8, 2011

This would hopefully be a multi-part series showing some tricks to enable claims-based-security in Silverlight 4.0. Silverlight 5.0 would have a much better story around claim-based-security as mentioned here.

In this first post, I’ll give you a high level overview of the solution. The main idea is to use the ‘WCF Routing Service’ in the DMZ to route both token issuance requests & business requests to the actual backend services.

1. Routing Service looks for a token issuing request and forwards it to the STS where the actual authentication is performed. After the successful authentication, STS issues a SAML token which goes back to Silverlight client via the routing service. Routing Service also terminates the SSL and backend is called using straight HTTP. This model offers strong security on the internet while keeping the internal deployment simpler & efficient. This model also resembles with the standard SSL offloading setup where a hardware load-balancer is used to terminate the SSL.

1: Token Issuance Path

image

2. Once the Silverlight client got a SAML token, it can attach it to all subsequent message sent to business service(s). Routing Services forwards al the business messages (messages which doesn’t match the token issuance filter) to the actual backend services again doing the protocol transitioning from HTTPS to HTTP. Please note, here you can use the rich filtering mechanism provided by the Routing services to decide which messages should to which services. I used a very simple MatchAll filter which forwards all the non-token-issuance messages to the business service.

2: Web Service Call Containing a SAML Token

image

To implement the 1st part of solution I have used the WSTrustClient class & the associated bindings from the identity training kit.

var vm = this.DataContext as MainPageViewModel;

var stsBinding = new WSTrustBindingUsernameMixed();

var stsCreds = new UsernameCredentials(vm.UserId, vm.Password);
var client = new WSTrustClient(
    stsBinding,
    new EndpointAddress(vm.SelectedEndpoint),
    stsCreds);

var rst = new RequestSecurityToken(WSTrust13Constants.KeyTypes.Bearer);
rst.AppliesTo = new EndpointAddress(vm.AppliesTo);

client.IssueCompleted += new System.EventHandler<IssueCompletedEventArgs>(client_IssueCompleted);
client.IssueAsync(rst);

For the 2nd part I have implemented a message inspector along with an extension method which makes it super easy to attach the SAML with outgoing messages.

var vm = this.DataContext as MainPageViewModel;
var client = new ServiceReference1.Service1Client();

client.AttachToken(vm.SecurityToken.RawToken);

client.GetDataCompleted += new EventHandler<ServiceReference1.GetDataCompletedEventArgs>(client_GetDataCompleted);
client.GetDataAsync(32);

Posted in Security, WCF, WIF | 10 Comments »

Securing WF 4 Workflow Services

Posted by zamd on February 3, 2011

If you interested in an in-depth understanding of workflow services along with various security options. Then check out my latest MSDN magazine article.

http://msdn.microsoft.com/en-gb/magazine/gg598919.aspx

Associated Source code

Posted in Uncategorized | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.