Defines the interface for a Custom Security Token Handler.
Пространство имен: Microsoft.IdentityModel.Tokens
Сборка: Microsoft.IdentityModel (в microsoft.identitymodel.dll)

Использование

Visual Basic
Dim instance As SecurityTokenHandler

Синтаксис

Visual Basic
Public MustInherit Class SecurityTokenHandler
C#
public abstract class SecurityTokenHandler
C++
public ref class SecurityTokenHandler abstract
J#
public abstract class SecurityTokenHandler
JScript
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
     Производные классы

Безопасность потоков

Любые открытые статические члены (Shared в Visual Basic) этого типа являются поточно-ориентированными.Любые члены экземпляров не являются гарантированно поточно-ориентированными.

Платформы

Платформа разработки

Windows Server 2003, Windows Vista

Target Platforms

Windows Server 2008, Windows Vista, Not tested on Windows XP

Change History

См. также