SecurityToken 类

定义

表示用于实现所有安全令牌的基类。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
继承
SecurityToken
派生

示例

本主题中使用的代码示例 SecurityToken 摘自 Custom Token 示例。The code examples that are used in the SecurityToken topics are taken from the Custom Token sample. 此示例提供了自定义类,这些类可用于处理简单 Web 标记 (SWT) 。This sample provides custom classes that enable processing of Simple Web Tokens (SWT). 它包含 SimpleWebToken 类和 SimpleWebTokenHandler 类以及支持 SWT 标记的其他类的实现。It includes an implementation of a SimpleWebToken class and a SimpleWebTokenHandler class, as well as other classes that support SWT tokens. 有关此示例和可供 WIF 使用的其他示例的信息,请参阅 WIF 代码示例索引For information about this sample and other samples available for WIF and about where to download them, see WIF Code Sample Index. 下面的代码演示类的实现 SimpleWebTokenThe following code shows the implementation of the SimpleWebToken class. 此类扩展 SecurityTokenThis 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 );
        } 
    }    
}

注解

使用安全令牌可提供身份验证凭据,也可以保护消息。Use a security token to provide authentication credentials or to protect a message.

安全令牌可用于提供身份验证凭据、加密密钥材料,如果 security token service (STS) 颁发安全令牌,则可以使用安全令牌来提供有关使用者的声明的集合。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. 所有安全令牌均派生自 SecurityToken 类。All security tokens derive from the SecurityToken class.

从 .NET 4.5 开始,Windows Identity Foundation (WIF) 已完全集成到 .NET Framework 中,WIF 公开的类是在代码中处理安全令牌的首选方法。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. 在 WIF 中,安全令牌从其 XML 表示形式进行序列化和反序列化,并通过使用派生自基类的类进行验证 SecurityTokenHandlerIn 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. 验证令牌不仅涉及确保令牌的有效性,还会 ClaimsIdentity 从令牌返回可用于进行身份验证和授权决策的实例。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. ClaimsIdentity是由标记处理程序的方法实现的,该 ValidateToken 方法由标记中包含的声明以及标记类型本身的内部声明来构造。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 附带了对以下类型的安全令牌的支持:WIF ships with support for the following types of security tokens:

  • Saml2SecurityToken:表示基于 SAML 2.0 断言的安全令牌。Saml2SecurityToken: Represents a security token that is based upon a SAML 2.0 Assertion. 此标记类型通常由 security token service 颁发,以响应 WS 信任或 WS 联合身份验证安全令牌请求 (RST) 。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:表示基于 SAML 1.1 断言的安全令牌。SamlSecurityToken: Represents a security token that is based upon a SAML 1.1 Assertion. 此标记类型通常由 security token service 颁发,以响应 WS 信任或 WS 联合身份验证安全令牌请求 (RST) 。This token type is typically issued by a security token service in response to a WS-Trust or WS-Federation security token request (RST).

  • KerberosRequestorSecurityTokenKerberosReceiverSecurityToken :表示基于在 SOAP 消息中接收或发送的 Kerberos 票证的安全令牌KerberosRequestorSecurityToken and KerberosReceiverSecurityToken: Represents a security token that is based upon a Kerberos ticket that is received or sent in a SOAP message

  • RsaSecurityToken:表示一个安全令牌,它基于使用 RSA 算法创建的密钥。RsaSecurityToken: Represents a security token that is based upon key that is created using the RSA algorithm.

  • SessionSecurityToken:表示包含会话相关信息的安全令牌。SessionSecurityToken: Represents a security token that contains information about a session.

  • UserNameSecurityToken:表示基于用户名和密码的安全令牌。UserNameSecurityToken: Represents a security token that is based on a username and password.

  • WindowsSecurityToken:表示基于 Windows 域或用户帐户标识的安全令牌。WindowsSecurityToken: Represents a security token that is based on the identity of a Windows domain or user account.

  • X509SecurityToken:表示基于 x.509 证书的安全令牌。X509SecurityToken: Represents a security token that is based on an X.509 certificate.

  • X509WindowsSecurityToken:表示一个安全令牌,该令牌基于映射到 Windows 域用户或本地计算机用户帐户的 x.509 证书。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.

另外两个安全令牌类( GenericXmlSecurityTokenEncryptedSecurityToken )可用于帮助处理一般情况。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. 例如 RsaSecurityToken ,和 X509SecurityToken 类型通常用于此目的。For example the RsaSecurityToken and X509SecurityToken types are often used for this purpose.

  • 表示已进行身份验证的用户的凭据的令牌。Tokens that represent credentials for users that have already been authenticated. 例如, UserNameSecurityToken WindowsSecurityToken 如果用户使用证书进行身份验证,则为、和 X509SecurityToken 类型。For example, the UserNameSecurityToken, WindowsSecurityToken, and, in the case of a user authenticated using a certificate, the X509SecurityToken types.

  • Security token service (STS) 颁发的令牌,以响应使用 WS-TRUST 或 WS 联合身份验证协议的安全令牌请求。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. 通常,它们在 wst:RequestSecurityTokenResponse XML 片段中返回。These are typically returned in a wst:RequestSecurityTokenResponse XML fragment. Saml2SecurityTokenSamlSecurityToken 类型通常用于表示这些标记。The Saml2SecurityToken and SamlSecurityToken types are most often used to represent these tokens.

特殊的标记类型, SessionSecurityToken 包含在主动或被动方案中使用会话时重新创建主体所需的信息。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. 若要添加对新标记类型的支持,可以直接从 SecurityToken 类派生。To add support for new token types, you can derive directly from the SecurityToken class. 当你执行此操作时,你还需要通过从类派生来创建令牌处理程序类 SecurityTokenHandlerWhen you do this, you will also need to create a token handler class by deriving from the SecurityTokenHandler class. 根据你使用令牌的方式,你可能还需要通过从类派生,并通过从类派生来创建自定义令牌解析程序,还需要创建 IssuerTokenResolver 一个或多个自定义密钥标识符子句类型 SecurityKeyIdentifierClauseDepending 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.

实施者说明

必须重写 IdSecurityKeysValidFromValidTo 属性。You must override the Id, SecurityKeys, ValidFrom, and ValidTo properties. CanCreateKeyIdentifierClause<T>()、、 CreateKeyIdentifierClause<T>() MatchesKeyIdentifierClause(SecurityKeyIdentifierClause)ResolveKeyIdentifierClause(SecurityKeyIdentifierClause) 方法都支持类型为的键标识符 LocalIdKeyIdentifierClauseThe 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.

构造函数

SecurityToken()

由派生类中的构造函数调用,用于初始化 SecurityToken 类。Called by constructors in derived classes to initialize the SecurityToken class.

属性

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.

方法

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.

(继承自 Object)
GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MatchesKeyIdentifierClause(SecurityKeyIdentifierClause)

返回一个值,该值指示此实例的密钥标识符能否解析为指定的密钥标识符。Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ResolveKeyIdentifierClause(SecurityKeyIdentifierClause)

为指定的密钥标识符子句获取密钥。Gets the key for the specified key identifier clause.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

适用于

另请参阅