Export (0) Print
Expand All

SecurityTokenHandler Class

Windows Identity Foundation
[Starting with the .NET Framework 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework. The version of WIF addressed by this topic, WIF 3.5, is deprecated and should only be used when developing against the .NET Framework 3.5 SP1 or the .NET Framework 4. For more information about WIF in the .NET Framework 4.5, also known as WIF 4.5, see the Windows Identity Foundation documentation in the .NET Framework 4.5 Development Guide.]

Defines the interface for a Custom Security Token Handler.


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

'Usage
Dim instance As SecurityTokenHandler

public abstract class SecurityTokenHandler
public abstract class SecurityTokenHandler
public abstract class SecurityTokenHandler



using (ServiceHost host = new ServiceHost(typeof(ClaimsAwareWebService), new Uri("http://localhost:6020/ClaimsAwareWebService")))
  {
     // Update the service credentials so that it can deserialize 
     // the custom token 
      ExtensibleServiceCredentials creds = new ExtensibleServiceCredentials();

CustomTokenHandler handler = new CustomTokenHandler();

// Add the custom token handler
      creds.TokenHandlers.Add( handler );

host.Description.Behaviors.Remove<ServiceCredentials>();
      host.Description.Behaviors.Add(creds);

      host.Open();

      Console.WriteLine(“Service is ready, press ENTER to close ...”);
      Console.ReadLine();

      host.Close()
   }


// Class that implements a custom security token handler

// This class derives from the SecurityTokenHandler class so that 
// the STS can issue a custom token.

    class CustomTokenHandler : SecurityTokenHandler
    {
        public const string TokenName = "MyDecisionToken";
        public const string Decision = "Decision";
        public const string TokenNamespace = "http://localhost/TokenNamespace";
        public const string Id = "Id";
        public const string Key = "Key";
        public const string DecisionClaimType = "http://localhost/DecisionClaimType";

// Define any necessary configurations 

        public CustomTokenHandler()
            : base()
        {
        }

// Implement the methods needed to handle validate/create of custom tokens

        /// <summary>
        /// This gets called by the STS to issue a token
        /// </summary>
        /// <param name="tokenDescriptor">The token descriptor.</param>
        /// <returns>The security token.</returns>
        public override SecurityToken CreateToken( SecurityTokenDescriptor tokenDescriptor )
        {
// Determine the claims that need to go in the token

// Create an instance of custom security token
// Custom security tokens are created by implementing a 
// class that derives from the SecurityToken class exposed 
// by WIF

SecurityToken token = MySecurityToken(…);
            
return token;
        }
        /// <summary>
        /// Gets the System.Type of the SecurityToken this instance handles.
        /// </summary>
        public override Type TokenType
        {
            get
            {
                return typeof(MySecurityToken);
            }
        }

        /// <summary>
        /// Gets the URI used in requests to identify a token of the type handled
        /// by this instance. 
        /// </summary>
        /// <remarks>
        /// For example, this should be the URI value used 
        /// in the RequestSecurityToken's TokenType element to request this
        /// sort of token.
        /// </remarks>
        public override string TokenTypeIdentifier
        {
            get
            {
                return “Custom Token Type”;
            }
        }

        /// <summary>
        /// This gets called on the STS to serialize the token 
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="token"></param>
        /// <param name="serializer"></param>
        /// <exception cref="ArgumentException">When the token is null.</exception>
        public override void WriteToken( XmlWriter writer, SecurityToken token, SecurityTokenSerializer serializer )
        {
            MySecurityToken decisionToken = token as MySecurityToken;

// Check for valid instance creation for decisionToken


// Create a signature writer to serialize the token
            EnvelopedSignatureWriter envWriter = new EnvelopedSignatureWriter( writer, decisionToken.SigningCredentials, decisionToken.Id, serializer ); 

            // Start the tokenName
            envWriter.WriteStartElement( TokenName, TokenNamespace );
            envWriter.WriteAttributeString( Id, token.Id );
            
            // Write the decision element
            envWriter.WriteElementString( Decision, TokenNamespace, Convert.ToString( decisionToken.Decision ) );

            // Write the key
            envWriter.WriteElementString( Key, TokenNamespace, Convert.ToBase64String( ( (MySecurityToken)token ).RetrieveKeyBytes() ) );
           
            // Close the TokenName element
            envWriter.WriteEndElement();
        }

        /// <summary>
        /// Indicates whether this handler supports validation of tokens 
        /// handled by this instance.
        /// </summary>
        /// <returns>true if the class is capable of SecurityToken
        /// validation.</returns>
        public override bool CanValidateToken
        {
            get { return true; }
        }

        /// <summary>
        /// Validates a token and returns its claims.
        /// </summary>
        /// <param name="token">The security token.</param>
        /// <returns>The collection of claims contained in the token.</returns>
        public override ClaimsIdentityCollection ValidateToken(SecurityToken token)
        {
                //
                // Generate the decision claim based on the decision
                //
                ClaimsIdentityCollection identities = new ClaimsIdentityCollection();

// Add necessary claims that need to be added in the 
// token

                return identities;
        }
    }

SecurityTokenHandler defines an interface for plugging custom token handling functionality. Using the SecurityTokenHandler you can add functionality to serialize, de-serialize, authenticate and create the token. The framework maintains a single copy of the SecurityTokenHandler for each token type. So custom token handlers should not have any state information associated with the handler.

Custom token handler can be registered in application configuration inside the <tokenHandlers> element or by adding it to the ExtensibleServiceCredentials.TokenHandlers collection programmatically.


System.Object
  Microsoft.IdentityModel.Tokens.SecurityTokenHandler
     Derived Classes

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

 

Target Platforms

Windows 7, Windows Server 2008 R2, Windows Vista SP2, Windows Server 2008 SP2, Windows Server 2003 SP2 (32-bit or 64-bit)



Copyright © 2008 by Microsoft Corporation. All rights reserved.

Community Additions

ADD
Show:
© 2014 Microsoft