Declarative Use of Custom SecurityTokenParameters

It's not the first time I've stated this, but one of the reasons I love WCF is that it's so wonderfully extensible. You can even implement your own custom security token, as this article explains. The only problem with this article is that it uses imperative code to create a custom Binding, and it doesn't explain how you can implement a custom security token mechanism in a declarative way (i.e. using app.config).

The offending part is the custom SecurityTokenParameters, which you can't specify declaratively, but have to attach to a SecurityBindingElement in some way.

So if you still want to be able to specify the use of your custom security token in app.config, how can you implement that?

A simple solution I've found involves creating a custom BindingElement that contains all the custom security token implementation, including the custom SecurityTokenParameters. This BindingElement additionally acts as a Decorator for whatever SecurityBindingElement you really want to use:

 public class CreditCardSecurityBindingElement : BindingElement
 {
     private readonly SymmetricSecurityBindingElement innerBindingElement_;
  
     public CreditCardSecurityBindingElement()
     {
         this.innerBindingElement_ = new SymmetricSecurityBindingElement();
         this.innerBindingElement_.EndpointSupportingTokenParameters.SignedEncrypted.Add(new CreditCardTokenParameters());
  
         //..
     }
  
     //..
 }

To fully implement your custom BindingElement, remember to override all its virtual methods to delegate the functionality to the inner SecurityBindingElement, like this:

 public override T GetProperty<T>(BindingContext context)
 {
     return this.innerBindingElement_.GetProperty<T>(context);
 }

To be able to use your custom BindingElement (CreditCardSecurityBindingElement) declaratively as part of a custom binding in app.config, you need to implement a BindingElementExtensionElement that creates it. Once you have done that, you should be good to go.