SecurityToken 클래스

정의

모든 보안 토큰을 구현하는 데 사용되는 기본 클래스를 나타냅니다.

public ref class SecurityToken abstract
public abstract class SecurityToken
type SecurityToken = class
Public MustInherit Class SecurityToken
상속
SecurityToken
파생

예제

에 사용 되는 코드 예제는 SecurityToken 항목에서 수행 되는 Custom Token 샘플. 이 샘플의 간단한 웹 토큰 (SWT) 처리를 사용 하도록 설정 하는 사용자 지정 클래스를 제공 합니다. 여기에는 클래스 및 SimpleWebTokenHandler 클래스의 SimpleWebToken 구현뿐만 아니라 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부터 WIF(Windows Identity Foundation)는 .NET Framework 완전히 통합되었으며 WIF에서 노출하는 클래스는 코드에서 보안 토큰을 처리하는 기본 방법입니다. WIF에서 보안 토큰은 XML 표현과 직렬화 및 역직렬화되며 기본 클래스에서 파생된 클래스를 사용하여 유효성을 SecurityTokenHandler 검사합니다. 토큰 유효성 검사에는 토큰이 유효한지 확인하는 것뿐만 아니라 인증 및 권한 부여 결정을 내리는 데 사용할 수 있는 토큰에서 instance 반환 ClaimsIdentity 하는 작업이 포함됩니다. 는 ClaimsIdentity 토큰에 포함된 클레임과 토큰 형식 자체에 내장된 클레임에서 메서드를 구현 ValidateToken 한 토큰 처리기에 의해 생성됩니다.

WIF는 다음과 같은 유형의 보안 토큰을 지원합니다.

  • Saml2SecurityToken: SAML 2.0 어설션을 기반으로 하는 보안 토큰을 나타냅니다. 이 토큰 유형은 일반적으로 WS-Trust 또는 WS-Federation RST(보안 토큰 요청)에 대한 응답으로 보안 토큰 서비스에서 발급됩니다.

  • SamlSecurityToken: SAML 1.1 어설션을 기반으로 하는 보안 토큰을 나타냅니다. 이 토큰 유형은 일반적으로 WS-Trust 또는 WS-Federation RST(보안 토큰 요청)에 대한 응답으로 보안 토큰 서비스에서 발급됩니다.

  • KerberosRequestorSecurityTokenKerberosReceiverSecurityToken: SOAP 메시지에서 수신되거나 전송되는 Kerberos 티켓을 기반으로 하는 보안 토큰을 나타냅니다.

  • RsaSecurityToken: RSA 알고리즘을 사용하여 만든 키를 기반으로 하는 보안 토큰을 나타냅니다.

  • SessionSecurityToken: 세션에 대한 정보를 포함하는 보안 토큰을 나타냅니다.

  • UserNameSecurityToken: 사용자 이름 및 암호를 기반으로 하는 보안 토큰을 나타냅니다.

  • WindowsSecurityToken: Windows 도메인 또는 사용자 계정의 ID를 기반으로 하는 보안 토큰을 나타냅니다.

  • X509SecurityToken: X.509 인증서를 기반으로 하는 보안 토큰을 나타냅니다.

  • X509WindowsSecurityToken: Windows 도메인 사용자 또는 로컬 컴퓨터 사용자 계정에 매핑되는 X.509 인증서를 기반으로 하는 보안 토큰을 나타냅니다.

다른 두 개의 보안 토큰 클래스인 GenericXmlSecurityTokenEncryptedSecurityToken를 사용하여 일반적인 사례를 처리할 수 있습니다.

대체로 보안 토큰은 다음 세 가지 주요 범주로 분류됩니다.

  • 암호화 키 자료를 전달하거나 참조하는 토큰입니다. 예를 들어 및 RsaSecurityTokenX509SecurityToken 형식은 이러한 용도로 자주 사용됩니다.

  • 이미 인증된 사용자의 자격 증명을 나타내는 토큰입니다. 예를 들어 , UserNameSecurityTokenWindowsSecurityToken및 는 인증서를 사용하여 인증된 사용자의 경우 형식입니다X509SecurityToken.

  • WS-Trust 또는 WS-Federation 프로토콜을 사용하여 보안 토큰 요청에 대한 응답으로 STS(보안 토큰 서비스)에서 발급한 토큰입니다. 이러한 항목은 일반적으로 XML 조각에 wst:RequestSecurityTokenResponse 반환됩니다. Saml2SecurityTokenSamlSecurityToken 형식은 이러한 토큰을 나타내는 데 가장 자주 사용됩니다.

특수 토큰 형식인 는 SessionSecurityToken활성 또는 수동 시나리오에서 세션을 사용할 때 보안 주체를 다시 만드는 데 필요한 정보를 포함합니다.

기존 토큰 형식에 기능을 추가하려면 특정 형식 및 관련 토큰 처리기에서 파생하여 토큰에 추가하는 새 요소를 지원할 수 있습니다. 새 토큰 형식에 대한 지원을 추가하려면 클래스에서 직접 파생할 SecurityToken 수 있습니다. 이렇게 하면 클래스에서 SecurityTokenHandler 파생하여 토큰 처리기 클래스를 만들어야 합니다. 토큰을 사용하는 방법에 따라 클래스에서 파생하여 사용자 지정 토큰 확인자와 클래스에서 IssuerTokenResolver 파생하여 하나 이상의 사용자 지정 키 식별자 절 형식을 SecurityKeyIdentifierClause 만들어야 할 수도 있습니다.

구현자 참고

, , SecurityKeysValidFromValidTo 속성을 재정의Id해야 합니다. , , 및 메서드는 CanCreateKeyIdentifierClause<T>()모두 형식LocalIdKeyIdentifierClause의 키 식별자를 지원합니다.ResolveKeyIdentifierClause(SecurityKeyIdentifierClause)MatchesKeyIdentifierClause(SecurityKeyIdentifierClause)CreateKeyIdentifierClause<T>() 파생 클래스의 다른 키 식별자 형식을 지원하려면 이러한 메서드를 재정의해야 합니다.

생성자

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)

적용 대상

추가 정보