SecurityTokenHandler.WriteToken 方法

定义

在派生类中重写时,将指定安全标记列化。 该标记必须是派生类处理的类型。

重载

WriteToken(SecurityToken)

在派生类中重写时,将指定安全标记列化到字符串。 该标记必须是派生类处理的类型。

WriteToken(XmlWriter, SecurityToken)

在派生类中重写时,将指定安全标记列化到 XML。 该标记必须是派生类处理的类型。

WriteToken(SecurityToken)

在派生类中重写时,将指定安全标记列化到字符串。 该标记必须是派生类处理的类型。

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

参数

token
SecurityToken

要序列化的标记。

返回

要序列化的标记。

注解

默认情况下,此方法引发 NotImplementedException 异常。

重写此方法以提供逻辑,以便将安全令牌序列化为 XML。 如果重写此方法,则还应重写 CanWriteToken 属性。

适用于

WriteToken(XmlWriter, SecurityToken)

在派生类中重写时,将指定安全标记列化到 XML。 该标记必须是派生类处理的类型。

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)

参数

writer
XmlWriter

XML 编写器。

token
SecurityToken

要序列化的标记。

示例

以下代码演示如何重写 WriteToken 方法以序列化自定义令牌。 代码取自示例 Custom Token 。 此示例提供自定义类,这些类支持处理简单 Web 令牌 (SWT) 。 有关此示例和可用于 WIF 的其他示例及其下载位置的信息,请参阅 WIF 代码示例索引

/// <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;
    }
}

注解

默认情况下,此方法引发 NotImplementedException 异常。

重写此方法以提供逻辑,以便将安全令牌序列化为 XML。 如果重写此方法,则还应重写 CanWriteToken 属性。

适用于