h1

Separate certificates for Transport and Message security in WCF

October 8, 2009

I’ve been busy of late writing my first book and doing so many other things that I haven’t had time to post anything on my blog. Now that I’ve got the book out of the way, I thought I should post something here. And what better topic than WCF :)

Recently, I had to interact with a financial institution using WCF for a Customer. The Service that the financial institution exposed was not written in WCF or .NET – not that it matters, but there were a number of specific things that had to be done to get it to work:

  • We needed to use transport security (https) that had to be encrypted using a specific X509 certificate
  • The body of the message had to be signed using another X509 certificate
  • The reply from the service did not have any security credentials attached to it – i.e. the transport was secure, but the message was not signed or encrypted

This may seem pretty straight forward – All you had to do is create a custom binding and specify something like this –

<custombinding>
  <binding name="Custom">
    <security messagesecurityversion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"
      authenticationmode="MutualCertificate"
    />
    <httpstransport requireclientcertificate="true"
      authenticationscheme="Negotiate"
      usedefaultwebproxy="true"
      manualaddressing="false"
    />
  </binding>
</custombinding>

The problem is that you can specify only one certificate in  Client credentials  and both message security as well as transport security will use the same certificate – we want to use two separate ones.

The solution to this is to add a new behavior that takes care of this. But rather than creating the behavior from scratch, an easier alternative is to extend the ClientCredentials class to cater for this additional certificate. So, I decided to use the existing certificate stored in ClientCredentials for message security and to add a separate property to hold the certificate for the Transport as shown in the code below –

///
/// Class that extends Client Credentials so that the certificate for the
/// Transport layer encryption can be separate
///
public class MyCredentials : ClientCredentials
{
  /// <summary>
  /// The X509 Certificate that is to be used for https
  /// </summary>
  public X509Certificate2 TransportCertificate { get; set; }

  public MyCredentials(ClientCredentials existingCredentials)
    : base(existingCredentials)
  {
  }

  protected MyCredentials(MyCredentials other)
    : base(other)
  {
    TransportCertificate = other.TransportCertificate;
  }

  protected override ClientCredentials CloneCore()
  {
    return new MyCredentials(this);
  }

  public override SecurityTokenManager CreateSecurityTokenManager()
  {
    return new MyCredentialsSecurityTokenManager(this);
  }

  public void SetTransportCertificate(string subjectName, StoreLocation storeLocation, StoreName storeName)
  {
    SetTransportCertificate(storeLocation, storeName, X509FindType.FindBySubjectDistinguishedName, subjectName);
  }

  public void SetTransportCertificate(StoreLocation storeLocation, StoreName storeName, X509FindType x509FindType, string subjectName)
  {
    TransportCertificate = FindCertificate(storeLocation, storeName, x509FindType, subjectName);
  }

  private static X509Certificate2 FindCertificate(StoreLocation location, StoreName name,
    X509FindType findType, string findValue)
  {
    X509Store store = new X509Store(name, location);
    try
    {
      store.Open(OpenFlags.ReadOnly);
      X509Certificate2Collection col = store.Certificates.Find(findType, findValue, true);
      return col[0]; // return first certificate found
    }
    finally
    {
      store.Close();
    }
  }

}

As part of the class, I added some helper methods to set the Transport certificate from code and also overrode the CreateSecurityTokenManager method so that I can create my own SecurityTokenManager that figures out which certificate to use for what operation.

But again, rather than create this class from scratch, I just extended the ClientCredentialsSecurityTokenManager class that ClientCredentials uses. In it I overrode the CreateSecurityTokenProvider method so that when a certificate is requested for Transport security, we pass back TransportCertificate that is stored in the MyCredentials object as shown in the code below -

internal class MyCredentialsSecurityTokenManager :
    ClientCredentialsSecurityTokenManager
{
    MyCredentials credentials;

    public MyCredentialsSecurityTokenManager(MyCredentials credentials)
        : base(credentials)
    {
        this.credentials = credentials;
    }

    public override SecurityTokenProvider CreateSecurityTokenProvider(
        SecurityTokenRequirement requirement)
    {
        SecurityTokenProvider result = null;

        if (requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.TransportSchemeProperty) &&
            requirement.TokenType == SecurityTokenTypes.X509Certificate)
        {
            result = new X509SecurityTokenProvider(
                this.credentials.TransportCertificate);
        }
        else if (requirement.KeyUsage == SecurityKeyUsage.Signature &&
            requirement.TokenType == SecurityTokenTypes.X509Certificate)
        {
            result = new X509SecurityTokenProvider(
                this.credentials.ClientCertificate.Certificate);
        }
        else
        {
            result = base.CreateSecurityTokenProvider(requirement);
        }

        return result;
    }

}

The last step is create the stuff necessary to be able to specify this in your config file. For that I extended the ClientCredentialsElement, so that I can specify the Transport Certificate as a behavior using the code below –

class ClientCredentialsExtensionElement : ClientCredentialsElement
{
    ConfigurationPropertyCollection properties;

    public override Type BehaviorType
    {
        get
        {
            return typeof(MyCredentials);
        }
    }

    [ConfigurationProperty("transportCertificate")]
    public X509InitiatorCertificateClientElement TransportCertificate
    {
        get
        {
            return base["transportCertificate"]
                as X509InitiatorCertificateClientElement;
        }
    }

    protected override ConfigurationPropertyCollection Properties
    {
        get
        {
            if (this.properties == null)
            {
                ConfigurationPropertyCollection properties = base.Properties;
                properties.Add(new ConfigurationProperty(
                    "transportCertificate",
                    typeof(X509InitiatorCertificateClientElement),
                    null, null, null,
                    ConfigurationPropertyOptions.None));
                this.properties = properties;
            }
            return this.properties;
        }
    }

    protected override object CreateBehavior()
    {
        MyCredentials creds = new MyCredentials(
            base.CreateBehavior() as ClientCredentials);

        PropertyInformationCollection properties =
            ElementInformation.Properties;

        creds.SetTransportCertificate(TransportCertificate.StoreLocation,
                                        TransportCertificate.StoreName,
                                        TransportCertificate.X509FindType,
                                        TransportCertificate.FindValue);

        base.ApplyConfiguration(creds);
        return creds;
    }
}

With the changes made, you should be able to replace the clientCredential section in your config file with the clientCredentialsExtension section. Something like this –



<system.serviceModel>
...
 <extensions>
   <behaviorExtensions>
     <add name="clientCredentialsExtension" type="MyNamespace.ClientCredentialsExtensionElement, MyAssemblyName" />
   </behaviorExtensions>

 </extensions>
 <behaviors>
   <endpointBehaviors>
     <behavior name="SecureMessageAndTransportBehavior">

       <clientCredentialsExtension>

         <!--This cert is used for signing the message-->
         <clientCertificate findValue="YourMessageCertName"
                            storeLocation ="LocalMachine"
                            storeName="My"
                            x509FindType="FindBySubjectName"
                            />

         <!--This cert is used for the transport-->
         <transportCertificate findValue="YourTransportCertName"
                            storeLocation ="LocalMachine"
                            storeName="My"
                            x509FindType="FindBySubjectName"
                            />

       </clientCredentialsExtension>

     </behavior>
   </endpointBehaviors>
 </behaviors>

</system.serviceModel>

That’s it – you are all set to go. Just make sure that you set this behavior for your endpoint.

h1

Speaking at SDDN on 30th June

June 21, 2009

I will be presenting on the new features in Expression Blend 3 at the Silverlight Designer and Developer Network (SDDN) on Tuesday the 30th of June, 2009 at 6:00pm. Here is the basic blurb for the talk –

Expression Blend 3 – What’s new?

Expression Blend 3 improves upon the goodness of Blend 2 SP 1 by providing a whole heap of new features and more importantly, the ability to create applications for Silverlight 3. The list of new enhancements is long – Lots of improvements to the way you use the tool, Improvements to how XAML, C# and VB.NET files are edited, Support for importing Adobe Photoshop and Illustrator files, Skinning enhancements, Enhancements for animation, Sample data generation, etc, etc.

Mahesh Krishnan will run through these changes in a fast demo based session (without using Powerpoint!) The session is targeted at both Designers and Developers, so don’t miss out :)

The venue is the Microsoft office in Melbourne.

h1

Talk on Application Architecture

May 7, 2009

I will be presenting on Application Architecture Guide on Tuesday the 12th of May, 2009 at the Victoria .NET Dev SIG. Here is the blurb for the talk -

Microsoft patterns and practices group released the Application Architecture Guide v2.0 early this year and Mahesh Krishnan walks us through what is present in the guide. He talks about the design-level guidance it offers, deployment patterns, different architectural styles, understanding quality requirements, archetypes and much much more.

You don’t have to be an architect to attend, so don’t miss out.

Attendance is free, but RSVP to info@victoriadotnet.com.au. So, if you happen to be in Melbourne, drop by to heckle or cheer :)

  • When: 12th May, 2009, 6:00pm. Be early for free pizzas :)
  • Where: Microsoft Theatre, Level 5, 4 Freshwater Place, Southbank

Tarn Barford will also be giving a talk on IronPython, which I am really looking forward to.

On the same night, we are also having a Windows 7 Install Fest with a bit of introduction on Win 7 given by Dave Glover. More details can be found on Dave Glover’s blog about the Install fest.

h1

Introduction to Windows Workflow

April 21, 2009

I created an Introduction to Windows Workflow presentation for the team and thought I’d share it here:

Windows Workflow Foundation – An Introduction

h1

"Introducing Microsoft® Silverlight™ 2" – Book review

April 20, 2009

I asked for MS Press to send me a copy of Lawrence Moroney’s Introducing Microsoft® Silverlight™ 2 book, so that I can review it. The idea was to give it away at the next SDDN user group meeting as a door prize.

9780735625280[1]

To start with, I was a bit disappointed that the book was still for the beta edition, rather than the release version of Silverlight 2. But there aren’t any radical changes between SL 2 Beta and Release, so I guess it is not too bad. (Lawrence Moroney has since made online updates to the book for the release version in his blog and has also been working on updates to SL 3 beta (which can be found here)

As the title of the book suggests, it is an introductory book, but even people with some knowledge of Silverlight will still find this useful.

The book itself is divided in to two parts – The first part covers the introductory topics and starts off by covering Expression Blend. After giving a thorough introduction to Blend, Lawrence moves on to Silverlight development using Visual Studio. Being an introductory book, I feel that Lawrence could have started off with a much simpler example (like a “Hello World”) – but he jumps right into a sliding block game. The book also assumes knowledge of C# and there aren’t any VB.NET examples. Being a C# person, myself. I didn’t mind this at all :) , but others may. The book then moves on to XAML and Lawrence does a good job talking about XAML shapes, brushes, transformations etc. and the last chapter in the first part – "Silverlight Browser" is particularly good.

The second part of the book is on Programming in Silverlight and Lawrence starts off talking about all the Silverlight controls including DataGrid, and the now defunct WatermarkedTextBoxControl. I haven’t had a look at Lawrence Moroney’s updates in his blog, but I would imagine that it addresses this and other breaking changes that were caused when Silverlight moved from Beta 1 to 2 and eventually to Release.

There are a couple of great chapters in Part 2 – “Building Connected Applications with Silverlight” and “Media, Ink and Deep Zoom”. Although I liked these chapters, they were probably a bit advanced for an introductory book. To add to it, there has been some changes to things like Deep Zoom composer. The “Building connected Applications..” chapter also includes some interesting sections on generating XAML using PHP and Java.

The chapter on Styles and Templates was a bit light on, particularly the section on templates. There could have also been a section on how to do some of these things using Expression Blend. The book finishes off with examples of creating Silverlight apps using dynamic languages such as Python and Ruby.

Although I’ve pointed out a few negative things as part of the review, the book on the whole is actually quite good and really worth a read and own for anyone wanting to start development in Silverlight 2.

Summary: A very good introductory book on Silverlight. Need a bit of knowledge on C#, but if you have any programming knowledge, you should be able to get by.

Rating: 4/5

Pros: Good strong introduction, Covers some advanced topics like using Silverlight with Java, PHP and dynamic languages

Cons: Does not have VB.NET examples. Very light on some topics like Data binding, Templates and Visual state manager.

h1

WPF Community Workshop

March 12, 2009

Ok, so you’ve seen Windows Presentation Foundation (WPF) and you thought the technology looked interesting. You know your applications are starting to look dated, you understand WPF has matured, now in its 3rd release; but life gets in the way and you haven’t had the chance to get down and dirty with it yet. So here’s your opportunity to skill up, and raise money for the Red Cross Bushfire Appeal, in this One-Day Workshop!!

To help you get to grips with this great technology quickly, Microsoft has created a series of Hands on Labs and Presentations. These will grow your skill set, putting you on the path to building the rich user interfaces your customers are demanding.

This training event comes to you courtesy of the .NET User Groups across Australia, and Cliftons, who are generously providing their training facilities at minimal cost. This is your chance to learn new skills, network with other professionals, and have a bit of fun along the way.

Registration and Payment

There is a nominal charge of $100. With the help of Cliftons we are keeping costs minimal and if we fill all workshops across the country then this event will raise close to $23,000 for the Red Cross “Victorian Bushfire Appeal 2009”.

Places are limited and to register interest please send a mail to mahesh dot krishnan at readify dot net

Workshop Format

To make it easy for you to attend we are running the workshops on a Saturday in all major cities. The sessions will commence at 8.30am with registration. Check the schedule below for the date and location in Melbourne.

Following a 10 to 15 minute introduction to each topic, you will kick start Visual Studio 2008 and Expression Blend and work on the relevant lab!! Regardless of your current level of experience, you can work at your own pace; a facilitator will be on hand to guide your learning; and you’ll be able to take the lab content home for further learning.

Content

The WPF Skills day will cover

  1. Creating layouts, compositions and templates
  2. Building custom controls
  3. Working with Styles and control templates (includes using Expression Blend to restyle)
  4. Using the Ribbon control to effortlessly create applications that are as familiar to your customers as Office 2007 (not to mention the Windows 7 Core Applications)
  5. Working with the new DataGrid control to display tabular and editable data
  6. Binding data with ease to your user interface
  7. And more…

Event Dates

The Windows Presentation Foundation Community workshop in Melbourne is to be held on Saturday, March 28th, 2009 at Cliftons on Collins Street.

Be in to Win

The workshop will also feature a prize draw to win a copy of Visual Studio 2008. Nice!!

So get clicking and sign up by sending a mail to mahesh dot krishnan at readify dot net and tell your mates about the day, learn something new and help out the Bushfire victims!!

h1

WCF Presentation slides

February 11, 2009

I’ve given a WCF presentation a number of times and every time some one asks me for the slide deck. And I keep saying that I’ll post it in my blog, but have been guilty of not doing it.

So, finally after a bit of prodding, I decided to post one. This one is called Practical WCF and is part 1 of a series. It gives a fair bit of introduction to WCF and also talks about Service contracts, Data contracts and Fault contracts.

Here is the link to download it: Practical WCF Part 1. ppsx

h1

Silverlight in a day – Update

February 11, 2009

We’ve had an overwhelming response for the Silverlight in a day event. Unfortunately, there are only a limited number of seats available. If you have been successful, you should be getting mails soon. If you haven’t been successful, we’ll let you know as well. Hopefully, we can run the event again and those who couldn’t find a place this time around can get one then.

The training will be facilitated by Philip Beadle, Jordan Knight and myself. As the trainer presents the lessons, the attendees will follow along on their own machine.

The following topics will be covered on the day:

  • Introduction to Silverlight
  • Introduction to XAML
  • Introduction to Expression Blend  / rest of Expression Suite
  • Layout controls
  • Advanced XAML concepts – Binding, Templates / reuse, Overview VSM / Parts + States Model
  • Networking
  • Media

Check out http://www.sddn.org.au for updates.

h1

Silverlight in a day

January 22, 2009

Jordan, Phil and I have been working towards running a full day community event in Melbourne to promote Silverlight as part of the Silverlight Developer and Designer Network (SDDN) and I am happy to announce some of the details:

The Event: Silverlight in a day

The SDDN invites you to come along and get your hands dirty with Silverlight 2! Learn how to build Silverlight Applications using Visual Studio and Expression Studio.

In this instructor led one day course the attendees will be able to work their way through hands-on labs and gain invaluable insight into the technology and how they can use it to create Rich Internet Applications (RIA).

Gain an understanding of varied Silverlight topics such as XAML, animation, data binding, communication and more and get the start you need to create great Silverlight applications!

Get in fast as spaces are limited…

When: Saturday 21st February 2009

Where: Cliftons on Collins St, Melbourne

Cost: $0. Nothing. Nada. FREE! (And we are trying to squeeze in a free lunch too – Whoever said there was no such thing as  free lunch?)

Contact: info @ sddn.org.au to reserve your spot!

I will provide more details about the event as and when they become available. A big thanks to ShaneMo, Joerg and the guys at Microsoft for making this event possible.

h1

Expression Blend for Silverlight Developers

October 21, 2008

That’s the title of my talk for RDN and here is the write up -

You don’t have to dress in black or wear turtle neck jumpers to use Expression Blend!

In this ReadiDepth session, Mahesh will show how developers can use Expression Blend to create rich Silverlight 2.0 user interfaces.

When and where is it on? Here are the details -

Sydney:

Wednesday 22 October, 6:00pm – 8:00pm
Cliftons, 190 George Street, Sydney

Melbourne:

Thursday 23 October, 6:00pm – 8:00pm
Cliftons, 440 Collins Street, Melbourne

Friday 24 October, 8:00am – 10:00am
Microsoft, Level 5, 4 Freshwater Place, Southbank

It is free to attend, but you need to register for the event first.