Rediger

Del via


SecurityToken Class

Definition

Represents a base class used to implement all security tokens.

public ref class SecurityToken abstract
public abstract class SecurityToken
type SecurityToken = class
Public MustInherit Class SecurityToken
Inheritance
SecurityToken
Derived

Examples

The code examples that are used in the SecurityToken topics are taken from the Custom Token sample. This sample provides custom classes that enable processing of Simple Web Tokens (SWT). It includes an implementation of a SimpleWebToken class and a SimpleWebTokenHandler class, as well as other classes that support SWT tokens. For information about this sample and other samples available for WIF and about where to download them, see WIF Code Sample Index. The following code shows the implementation of the SimpleWebToken class. This class extends SecurityToken.

/// <summary>
/// Defines the set of constants for the Simple Web Token.
/// </summary>
public static class SimpleWebTokenConstants
{
    public const string Audience = "Audience";
    public const string ExpiresOn = "ExpiresOn";
    public const string Id = "Id";
    public const string Issuer = "Issuer";
    public const string Signature = "HMACSHA256";
    public const string ValidFrom = "ValidFrom";
    public const string ValueTypeUri = "http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0";     
}
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IdentityModel.Tokens;

namespace SimpleWebToken
{
    /// <summary>
    /// This class represents the token format for the SimpleWebToken.
    /// </summary>
    public class SimpleWebToken : SecurityToken
    {
        public static DateTime SwtBaseTime = new DateTime( 1970, 1, 1, 0, 0, 0, 0 ); // per SWT psec

        NameValueCollection _properties;
        string _serializedToken;

        /// <summary>
        /// Initializes a new instance of the <see cref="SimpleWebToken"/> class.
        /// This is an internal constructor that is only called from the <see cref="SimpleWebTokenHandler"/> when reading a token received from the wire.
        /// </summary>
        /// <param name="properties">The collection representing all the key value pairs in the token.</param>
        /// <param name="serializedToken">The serialized form of the token.</param>
        internal SimpleWebToken( NameValueCollection properties, string serializedToken )
            : this(properties)
        {
            _serializedToken = serializedToken;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SimpleWebToken"/> class.
        /// </summary>
        /// <param name="properties">The collection representing all the key value pairs in the token.</param>
        public SimpleWebToken( NameValueCollection properties )
        {
            if ( properties == null )
            {
                throw new ArgumentNullException( "properties" );
            }

            _properties = properties;
        }

        /// <summary>
        /// Gets the Id of the token.
        /// </summary>
        /// <value>The Id of the token.</value>
        public override string Id
        {
            get 
            {
                return _properties[SimpleWebTokenConstants.Id];
            }
        }

        /// <summary>
        /// Gets the keys associated with this token.
        /// </summary>
        /// <value>The keys associated with this token.</value>
        public override ReadOnlyCollection<SecurityKey> SecurityKeys
        {
            get 
            { 
                return new ReadOnlyCollection<SecurityKey>( new List<SecurityKey>() ); 
            }
        }

        /// <summary>
        /// Gets the time from when the token is valid.
        /// </summary>
        /// <value>The time from when the token is valid.</value>
        public override DateTime ValidFrom
        {
            get 
            {
                string validFrom = _properties[SimpleWebTokenConstants.ValidFrom];
                return GetTimeAsDateTime( String.IsNullOrEmpty( validFrom ) ? "0" : validFrom );
            }
        }

        /// <summary>
        /// Gets the time when the token expires.
        /// </summary>
        /// <value>The time up to which the token is valid.</value>
        public override DateTime ValidTo
        {
            get
            {
                string expiryTime = _properties[SimpleWebTokenConstants.ExpiresOn];
                return GetTimeAsDateTime( String.IsNullOrEmpty( expiryTime ) ? "0" : expiryTime );
            }
        }

        /// <summary>
        /// Gets the Audience for the token.
        /// </summary>
        /// <value>The audience of the token.</value>
        public string Audience
        {
            get 
            {
                return _properties[SimpleWebTokenConstants.Audience];
            }
        }

        /// <summary>
        /// Gets the Issuer for the token.
        /// </summary>
        /// <value>The issuer for the token.</value>
        public string Issuer
        {
            get 
            { 
                return _properties[SimpleWebTokenConstants.Issuer]; 
            }
        }

        /// <summary>
        /// Gets the signature for the token.
        /// </summary>
        /// <value>The signature for the token.</value>
        public string Signature
        {
            get 
            { 
                return _properties[SimpleWebTokenConstants.Signature]; 
            }
        }

        /// <summary>
        /// Gets the serialized form of the token if the token was created from its serialized form by the token handler.
        /// </summary>
        /// <value>The serialized form of the token.</value>
        public string SerializedToken
        {
            get
            {
                return _serializedToken;
            }
        }

        /// <summary>
        /// Creates a copy of all key value pairs of the token.
        /// </summary>
        /// <returns>A copy of all the key value pairs in the token.</returns>
        public NameValueCollection GetAllProperties()
        {
            return new NameValueCollection( _properties );
        }

        /// <summary>
        /// Converts the time in seconds to a <see cref="DateTime"/> object based on the base time 
        /// defined by the Simple Web Token.
        /// </summary>
        /// <param name="expiryTime">The time in seconds.</param>
        /// <returns>The time as a <see cref="DateTime"/> object.</returns>
        protected virtual DateTime GetTimeAsDateTime( string expiryTime )
        {
            long totalSeconds = 0;
            if ( !long.TryParse( expiryTime, out totalSeconds ) )
            {
                throw new SecurityTokenException("Invalid expiry time. Expected the time to be in seconds passed from 1 January 1970.");
            }

            long maxSeconds = (long)( DateTime.MaxValue - SwtBaseTime ).TotalSeconds - 1;
            if ( totalSeconds > maxSeconds )
            {
                totalSeconds = maxSeconds;
            }

            return SwtBaseTime.AddSeconds( totalSeconds );
        } 
    }    
}

Remarks

Use a security token to provide authentication credentials or to protect a message.

A security token can be used to provide authentication credentials, cryptographic key material, or, in the case of a security token issued by a security token service (STS), a collection of claims about a subject. All security tokens derive from the SecurityToken class.

Beginning with .NET 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework and the classes exposed by WIF are the preferred method of handling security tokens in your code. In WIF, security tokens are serialized and deserialized to and from their XML representation and are validated by using classes derived from the SecurityTokenHandler base class. Validating a token involves not just ensuring that the token is valid, but also returning a ClaimsIdentity instance from the token that can be used in making authentication and authorization decisions. The ClaimsIdentity is constructed by the token handler's implementation of the ValidateToken method from the claims contained in the token as well as from claims that are intrinsic to the token type itself.

WIF ships with support for the following types of security tokens:

  • Saml2SecurityToken: Represents a security token that is based upon a SAML 2.0 Assertion. This token type is typically issued by a security token service in response to a WS-Trust or WS-Federation security token request (RST).

  • SamlSecurityToken: Represents a security token that is based upon a SAML 1.1 Assertion. This token type is typically issued by a security token service in response to a WS-Trust or WS-Federation security token request (RST).

  • KerberosRequestorSecurityToken and KerberosReceiverSecurityToken: Represents a security token that is based upon a Kerberos ticket that is received or sent in a SOAP message

  • RsaSecurityToken: Represents a security token that is based upon key that is created using the RSA algorithm.

  • SessionSecurityToken: Represents a security token that contains information about a session.

  • UserNameSecurityToken: Represents a security token that is based on a username and password.

  • WindowsSecurityToken: Represents a security token that is based on the identity of a Windows domain or user account.

  • X509SecurityToken: Represents a security token that is based on an X.509 certificate.

  • X509WindowsSecurityToken: Represents a security token that is based upon an X.509 certificate that is mapped to a Windows domain user or local computer user account.

Two other security token classes, GenericXmlSecurityToken and EncryptedSecurityToken, can be used to help handle general cases.

Broadly speaking security tokens fall into three major categories:

  • Tokens that carry or reference cryptographic key material. For example the RsaSecurityToken and X509SecurityToken types are often used for this purpose.

  • Tokens that represent credentials for users that have already been authenticated. For example, the UserNameSecurityToken, WindowsSecurityToken, and, in the case of a user authenticated using a certificate, the X509SecurityToken types.

  • Tokens that are issued by a security token service (STS) in response to a security token request using either the WS-Trust or WS-Federation protocol. These are typically returned in a wst:RequestSecurityTokenResponse XML fragment. The Saml2SecurityToken and SamlSecurityToken types are most often used to represent these tokens.

A special token type, the SessionSecurityToken, contains information necessary to recreate a principal when using sessions in active or passive scenarios.

To add functionality to existing token types you can derive from the specific type and its associated token handler to support any new elements that you add to the token. To add support for new token types, you can derive directly from the SecurityToken class. When you do this, you will also need to create a token handler class by deriving from the SecurityTokenHandler class. Depending on how your token is to be used, you may also need to create a custom token resolver by deriving from the IssuerTokenResolver class as well as one or more custom key identifier clause types by deriving from the SecurityKeyIdentifierClause class.

Notes to Implementers

You must override the Id, SecurityKeys, ValidFrom, and ValidTo properties. The CanCreateKeyIdentifierClause<T>(), CreateKeyIdentifierClause<T>(), MatchesKeyIdentifierClause(SecurityKeyIdentifierClause), and ResolveKeyIdentifierClause(SecurityKeyIdentifierClause) methods all support key identifiers of type LocalIdKeyIdentifierClause. You must override these methods to support other key identifier types in your derived class.

Constructors

SecurityToken()

Called by constructors in derived classes to initialize the SecurityToken class.

Properties

Id

Gets a unique identifier of the security token.

SecurityKeys

Gets the cryptographic keys associated with the security token.

ValidFrom

Gets the first instant in time at which this security token is valid.

ValidTo

Gets the last instant in time at which this security token is valid.

Methods

CanCreateKeyIdentifierClause<T>()

Gets a value that indicates whether this security token is capable of creating the specified key identifier.

CreateKeyIdentifierClause<T>()

Creates the specified key identifier clause.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
MatchesKeyIdentifierClause(SecurityKeyIdentifierClause)

Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ResolveKeyIdentifierClause(SecurityKeyIdentifierClause)

Gets the key for the specified key identifier clause.

ToString()

Returns a string that represents the current object.

(Inherited from Object)

Applies to

See also