In some sophisticated scenarios there might be requirement to implement the custom security header. Because this
is not well documented in WCF documentation I decided to post one the example. By implementing of custom security
there will be some custom security token like MySecurityTokenHeader shown in the next example.
In general to implement any kind of header in WCF the customization class has to derive from MessageHeader.
internal class MySecurityTokenHeader : MessageHeader { /// <summary> /// This method is called by WCF during serialization of the message, /// when the custom security header has to be created. /// It traverses trough all created security tokens /// and append them to the message header. /// </summary> /// <param name="writer"></param> /// <param name="messageVersion"></param> protected override void OnWriteHeaderContents(System.Xml.XmlDictionaryWriter writer, MessageVersion messageVersion) { foreach (SecurityToken token in m_SomeCustomSecurityTokens) { MySecurityTokenSerializer tokenSerializer = new MySecurityTokenSerializer(token, this.m_MessageVersion); tokenSerializer.WriteToken(writer, token); } } /// <summary> /// The name of the element describing the security header. /// </summary> public override string Name { get { return ElementContainer.Security; } } /// <summary> /// Namespace of the security header. /// </summary> public override string Namespace { get { return NamspaceContainer.WssSecuritySecext; } } } |
The most important method is OnWriteHeaderContents. It is responsible to create the header with any custom content.
In this example I append many custom security tokens. However, for this purpose the class MySecurityTokenSerializer
is used.
Following example shows how to implement the custom security token serializer which is automatically invoked by Service Model,
when the custom SecurityHeader has to be serialized.
internal class MySecurityTokenSerializer : WSSecurityTokenSerializer { private SecurityToken m_Token;
public MySecurityTokenSerializer(SecurityToken token, SecurityVersion version) : base(version) { m_Token = token; }
///<summary> /// Writes the specified security token using the specified XML writer. Called /// by the base class. ///</summary> ///<param name="writer">The writer used to wite the token data.</param> ///<param name="token">The security token which should be serialized.</param>
protected override void WriteTokenCore(XmlWriter writer, SecurityToken token)
{
if (m_Token is XmlSecurityToken)
serializeSbbSamlToken(writer, token as XmlSecurityToken);
else
base.WriteTokenCore(writer, token);
}
private void serializeSbbSamlToken(XmlWriter writer, XmlSecurityToken token)
{
XmlNodeReader reader = new XmlNodeReader(someXmlElementContainingTheToken);
writer.WriteNode(reader, true);
}
}
|
Posted
May 23 2007, 02:19 PM
by
Damir Dobric