SecurityTokenHandler.ReadToken Method (XmlReader)

.NET Framework (current version)

When overridden in a derived class, deserializes the XML referenced by the specified XML reader to a token of the type processed by the derived class.

Namespace:   System.IdentityModel.Tokens
Assembly:  System.IdentityModel (in System.IdentityModel.dll)

Public Overridable Function ReadToken (
	reader As XmlReader
) As SecurityToken


Type: System.Xml.XmlReader

An XML reader positioned at the start element of the token.

Return Value

Type: System.IdentityModel.Tokens.SecurityToken

The security token that was deserialized from the XML.

System_CAPS_security Security Note

Calling this method with untrusted data is a security risk. Call this method only with trusted data. For more information, see Untrusted Data Security Risks.

By default this method throws a NotImplementedException exception.

Override this method to provide the logic to deserialize a security token from XML. If you override this method, you should also override the SecurityTokenHandler.CanReadToken method. Typically, in derived classes, if the method cannot deserialize the token from the referenced XML, it throws an XmlException.

The following code shows how to override the ReadToken method to read a custom token from the specified XML reader. 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>
/// Reads a serialized token and converts it into a <see cref="SecurityToken"/>.
/// </summary>
/// <param name="reader">An XML reader positioned at the token's start element.</param>
/// <returns>The parsed form of the token.</returns>
public override SecurityToken ReadToken( XmlReader reader )
    if ( reader == null )
        throw new ArgumentNullException( "reader" );

    XmlDictionaryReader dictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader);

    byte[] binaryData;
    string encoding = dictionaryReader.GetAttribute( EncodingType );
    if ( encoding == null || encoding == Base64EncodingType )
        binaryData = dictionaryReader.ReadContentAsBase64();
        throw new SecurityTokenException(
            "Cannot read SecurityToken as its encoding is" + encoding + ". Expected a BinarySecurityToken with base64 encoding.");

    string serializedToken = Encoding.UTF8.GetString(binaryData);

    return ReadSecurityTokenFromString(serializedToken);
/// <summary>
/// Parse the string token and generates a <see cref="SecurityToken"/>.
/// </summary>
/// <param name="serializedToken">The serialized form of the token received.</param>
/// <returns>The parsed form of the token.</returns>
protected SecurityToken ReadSecurityTokenFromString( string serializedToken )
    if (String.IsNullOrEmpty(serializedToken))
        throw new ArgumentException("The parameter 'serializedToken' cannot be null or empty string.");

    // Create a collection of SWT name value pairs
    NameValueCollection properties = ParseToken( serializedToken );
    SimpleWebToken swt = new SimpleWebToken( properties, serializedToken );

    return swt;
/// <summary>
/// Parses the token into a collection.
/// </summary>
/// <param name="encodedToken">The serialized token.</param>
/// <returns>A colleciton of all name-value pairs from the token.</returns>
NameValueCollection ParseToken( string encodedToken )
    if ( String.IsNullOrEmpty( encodedToken ) )
        throw new ArgumentException( "The parameter 'encodedToken' cannot be null or empty string.");

    NameValueCollection keyValuePairs = new NameValueCollection();
    foreach ( string nameValue in encodedToken.Split( ParameterSeparator ) )
        string[] keyValueArray = nameValue.Split( '=' );

        if ( ( keyValueArray.Length < 2 ) || String.IsNullOrEmpty( keyValueArray[0] ) )
            throw new SecurityTokenException("The incoming token was not in an expected format.");

        // Names must be decoded for the claim type case
        string key = HttpUtility.UrlDecode( keyValueArray[0].Trim() );

        // remove any unwanted "
        string value = HttpUtility.UrlDecode( keyValueArray[1].Trim().Trim( '"' ) ); 
        keyValuePairs.Add( key, value );

    return keyValuePairs;

.NET Framework
Available since 4.5
Return to top