Ask Learn
Preview
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
When overridden in a derived class, serializes the specified security token. The token must be of the type processed by the derived class.
WriteToken(SecurityToken) |
When overridden in a derived class, serializes the specified security token to a string. The token must be of the type processed by the derived class. |
WriteToken(XmlWriter, SecurityToken) |
When overridden in a derived class, serializes the specified security token to XML. The token must be of the type processed by the derived class. |
When overridden in a derived class, serializes the specified security token to a string. The token must be of the type processed by the derived class.
public:
virtual System::String ^ WriteToken(System::IdentityModel::Tokens::SecurityToken ^ token);
public virtual string WriteToken(System.IdentityModel.Tokens.SecurityToken token);
abstract member WriteToken : System.IdentityModel.Tokens.SecurityToken -> string
override this.WriteToken : System.IdentityModel.Tokens.SecurityToken -> string
Public Overridable Function WriteToken (token As SecurityToken) As String
The token to serialize.
The serialized token.
By default this method throws a NotImplementedException exception.
Override this method to provide the logic to serialize a security token to XML. If you override this method, you should also override the CanWriteToken property.
Product | Versions |
---|---|
.NET Framework | 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
When overridden in a derived class, serializes the specified security token to XML. The token must be of the type processed by the derived class.
public:
virtual void WriteToken(System::Xml::XmlWriter ^ writer, System::IdentityModel::Tokens::SecurityToken ^ token);
public virtual void WriteToken(System.Xml.XmlWriter writer, System.IdentityModel.Tokens.SecurityToken token);
abstract member WriteToken : System.Xml.XmlWriter * System.IdentityModel.Tokens.SecurityToken -> unit
override this.WriteToken : System.Xml.XmlWriter * System.IdentityModel.Tokens.SecurityToken -> unit
Public Overridable Sub WriteToken (writer As XmlWriter, token As SecurityToken)
The XML writer.
The token to serialize.
The following code shows how to override the WriteToken method to serialize a custom token. The code is taken from the Custom Token
sample. This sample provides custom classes that enable processing of Simple Web Tokens (SWT). For information about this sample and other samples available for WIF and where to download them, see WIF Code Sample Index.
/// <summary>
/// Serializes the given SecurityToken to the XmlWriter.
/// </summary>
/// <param name="writer">XmlWriter into which the token is serialized.</param>
/// <param name="token">SecurityToken to be serialized.</param>
public override void WriteToken( XmlWriter writer, SecurityToken token )
{
SimpleWebToken simpleWebToken = token as SimpleWebToken;
if ( simpleWebToken == null )
{
throw new SecurityTokenException("The given token is not of the expected type 'SimpleWebToken'.");
}
string signedToken = null;
if ( String.IsNullOrEmpty( simpleWebToken.SerializedToken ) )
{
StringBuilder strBuilder = new StringBuilder();
bool skipDelimiter = true;
NameValueCollection tokenProperties = simpleWebToken.GetAllProperties();
// remove the signature if present
if ( String.IsNullOrEmpty( tokenProperties[SimpleWebTokenConstants.Signature] ) )
{
tokenProperties.Remove( SimpleWebTokenConstants.Signature );
}
foreach ( string key in tokenProperties.Keys )
{
if ( tokenProperties[key] != null )
{
if ( !skipDelimiter )
{
strBuilder.Append( ParameterSeparator );
}
strBuilder.Append( String.Format(
CultureInfo.InvariantCulture,
"{0}={1}",
HttpUtility.UrlEncode( key ),
HttpUtility.UrlEncode( tokenProperties[key] ) ) );
skipDelimiter = false;
}
}
string serializedToken = strBuilder.ToString();
SimpleWebTokenKeyIdentifierClause clause = new SimpleWebTokenKeyIdentifierClause(simpleWebToken.Audience);
InMemorySymmetricSecurityKey securityKey = null;
try
{
securityKey = (InMemorySymmetricSecurityKey)this.Configuration.IssuerTokenResolver.ResolveSecurityKey(clause);
}
catch (InvalidOperationException)
{
throw new SecurityTokenValidationException("A Symmetric key was not found for the given key identifier clause.");
}
// append the signature
string signature = GenerateSignature( serializedToken, securityKey.GetSymmetricKey() );
strBuilder.Append( String.Format(
CultureInfo.InvariantCulture,
"{0}{1}={2}",
ParameterSeparator,
HttpUtility.UrlEncode( SimpleWebTokenConstants.Signature ),
HttpUtility.UrlEncode( signature ) ) );
signedToken = strBuilder.ToString();
}
else
{
// reuse the stored serialized token if present
signedToken = simpleWebToken.SerializedToken;
}
string encodedToken = Convert.ToBase64String( Encoding.UTF8.GetBytes( signedToken ) );
writer.WriteStartElement(BinarySecurityToken);
writer.WriteAttributeString("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", token.Id);
writer.WriteAttributeString( ValueType, SimpleWebTokenConstants.ValueTypeUri );
writer.WriteAttributeString( EncodingType, Base64EncodingType );
writer.WriteString( encodedToken );
writer.WriteEndElement();
}
/// <summary>
/// Generates an HMACSHA256 signature for a given string and key.
/// </summary>
/// <param name="unsignedToken">The token to be signed.</param>
/// <param name="signingKey">The key used to generate the signature.</param>
/// <returns>The generated signature.</returns>
protected static string GenerateSignature(string unsignedToken, byte[] signingKey)
{
using (HMACSHA256 hmac = new HMACSHA256(signingKey))
{
byte[] signatureBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(unsignedToken));
string signature = HttpUtility.UrlEncode(Convert.ToBase64String(signatureBytes));
return signature;
}
}
By default this method throws a NotImplementedException exception.
Override this method to provide the logic to serialize a security token to XML. If you override this method, you should also override the CanWriteToken property.
Product | Versions |
---|---|
.NET Framework | 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign in