SecurityToken 类

定义

表示用于实现所有安全令牌的基类。

public ref class SecurityToken abstract
public abstract class SecurityToken
type SecurityToken = class
Public MustInherit Class SecurityToken
继承
SecurityToken
派生

示例

主题中使用的 SecurityToken 代码示例取自 Custom Token 示例。 此示例提供允许处理简单 Web 令牌(SWT)的自定义类。 它包括类和SimpleWebToken类的SimpleWebTokenHandler实现,以及支持 SWT 令牌的其他类。 有关此示例和其他可用于 WIF 的示例以及下载位置的信息,请参阅 WIF 代码示例索引。 以下代码显示了类的 SimpleWebToken 实现。 此类扩展 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 );
        } 
    }    
}

注解

使用安全令牌提供身份验证凭据或保护消息。

安全令牌可用于提供身份验证凭据、加密密钥材料,或者在安全令牌服务(STS)颁发的安全令牌的情况下,提供有关主体的声明集合。 所有安全令牌都派生自 SecurityToken 该类。

从 .NET 4.5 开始,Windows Identity Foundation (WIF)已完全集成到 .NET Framework 中,WIF 公开的类是处理代码中安全令牌的首选方法。 在 WIF 中,安全令牌在 XML 表示形式中序列化和反序列化,并使用派生自基类的 SecurityTokenHandler 类进行验证。 验证令牌不仅涉及确保令牌有效,还涉及从令牌返回 ClaimsIdentity 实例,这些实例可用于做出身份验证和授权决策。 这是 ClaimsIdentity 由令牌处理程序 ValidateToken 从令牌中包含的声明以及令牌类型本身固有的声明中实现方法构造的。

WIF 附带了对以下安全令牌类型的支持:

另外两个安全令牌类 GenericXmlSecurityTokenEncryptedSecurityToken可用于帮助处理一般情况。

从广义上讲,安全令牌分为三大类:

  • 携带或引用加密密钥材料的令牌。 例如,此类 RsaSecurityTokenX509SecurityToken 类型通常用于此目的。

  • 表示已进行身份验证的用户凭据的令牌。 例如,在使用证书进行身份验证的用户时,类型为 <a0/>

  • 由安全令牌服务(STS)颁发的令牌,以响应使用 WS-Trust 或 WS-Federation 协议的安全令牌请求。 这些通常在 XML 片段中 wst:RequestSecurityTokenResponse 返回。 SamlSecurityTokenSaml2SecurityToken类型最常用于表示这些令牌。

特殊令牌类型 SessionSecurityToken包含在主动或被动方案中使用会话时重新创建主体所需的信息。

若要向现有令牌类型添加功能,可以从特定类型及其关联的令牌处理程序派生,以支持添加到令牌的任何新元素。 若要添加对新令牌类型的支持,可以直接从 SecurityToken 类派生。 执行此操作时,还需要通过派生自 SecurityTokenHandler 类来创建令牌处理程序类。 根据令牌的使用方式,可能还需要通过从 IssuerTokenResolver 类派生以及从类派生 SecurityKeyIdentifierClause 一个或多个自定义密钥标识符子句类型来创建自定义令牌解析程序。

实施者说明

必须重写 IdSecurityKeys属性 ValidFromValidTo 属性。 和CanCreateKeyIdentifierClause<T>()ResolveKeyIdentifierClause(SecurityKeyIdentifierClause)CreateKeyIdentifierClause<T>()MatchesKeyIdentifierClause(SecurityKeyIdentifierClause)方法都支持类型的LocalIdKeyIdentifierClause密钥标识符。 必须重写这些方法以支持派生类中的其他密钥标识符类型。

构造函数

名称 说明
SecurityToken()

由派生类中的构造函数调用以初始化 SecurityToken 类。

属性

名称 说明
Id

获取安全令牌的唯一标识符。

SecurityKeys

获取与安全令牌关联的加密密钥。

ValidFrom

获取此安全令牌有效的第一个即时时间。

ValidTo

获取此安全令牌有效的最后一刻。

方法

名称 说明
CanCreateKeyIdentifierClause<T>()

获取一个值,该值指示此安全令牌是否能够创建指定的密钥标识符。

CreateKeyIdentifierClause<T>()

创建指定的密钥标识符子句。

Equals(Object)

确定指定的对象是否等于当前对象。

(继承自 Object)
GetHashCode()

用作默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
MatchesKeyIdentifierClause(SecurityKeyIdentifierClause)

返回一个值,该值指示是否可以将此实例的密钥标识符解析为指定的密钥标识符。

MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
ResolveKeyIdentifierClause(SecurityKeyIdentifierClause)

获取指定密钥标识符子句的密钥。

ToString()

返回一个表示当前对象的字符串。

(继承自 Object)

适用于

另请参阅