SecurityTokenService 클래스

정의

STS(보안 토큰 서비스)의 속성과 메서드를 정의하는 추상 기본 클래스입니다.

public ref class SecurityTokenService abstract
public abstract class SecurityTokenService
type SecurityTokenService = class
Public MustInherit Class SecurityTokenService
상속
SecurityTokenService

예제

토픽에 SecurityTokenService 사용되는 코드 예제는 샘플에서 Custom Token 가져옵니다. 이 샘플에서는 SWT(Simple Web Tokens)를 처리할 수 있는 사용자 지정 클래스를 제공하며 SWT 토큰을 제공할 수 있는 수동 STS의 구현을 포함합니다. 활성 STS를 구현하는 방법의 예제는 샘플을 볼 Federation Metadata 수 있습니다. WIF에 사용할 수 있는 이러한 샘플 및 기타 샘플 및 다운로드 위치에 대한 자세한 내용은 WIF 코드 샘플 인덱스(Sample Index)를 참조하세요. 다음 코드는 클래스를 사용하는 수동 STS의 구현을 보여 줍니다 SecurityTokenService .

using System;
using System.IdentityModel;
using System.IdentityModel.Configuration;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Tokens;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;

namespace PassiveSTS
{
    /// <summary>
    /// Overrides the SecurityTokenService class to provide
    /// the relying party related information, such as encryption credentials to encrypt the issued
    /// token, signing credentials to sign the issued token, claims that the STS wants to issue for a 
    /// certain token request, as well as the claim types that this STS is capable
    /// of issuing.
    /// </summary>
    public class CustomSecurityTokenService : SecurityTokenService
    {
        // Certificate Constants
        private const string SIGNING_CERTIFICATE_NAME = "CN=localhost";
        private const string ENCRYPTING_CERTIFICATE_NAME = "CN=localhost";

        private SigningCredentials _signingCreds;
        private EncryptingCredentials _encryptingCreds;
        // Used for validating applies to address, set to URI used in RP app of application, could also have been done via config
        private string _addressExpected = "http://localhost:19851/";
        public CustomSecurityTokenService(SecurityTokenServiceConfiguration configuration)
            : base(configuration)
        {
            // Setup the certificate our STS is going to use to sign the issued tokens
            _signingCreds = new X509SigningCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, SIGNING_CERTIFICATE_NAME));

            // Note: In this sample app only a si   ngle RP identity is shown, which is localhost, and the certificate of that RP is 
            // populated as _encryptingCreds
            // If you have multiple RPs for the STS you would select the certificate that is specific to 
            // the RP that requests the token and then use that for _encryptingCreds
            _encryptingCreds = new X509EncryptingCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, ENCRYPTING_CERTIFICATE_NAME));
        }

        /// <summary>
        /// This method returns the configuration for the token issuance request. The configuration
        /// is represented by the Scope class. In our case, we are only capable of issuing a token to a
        /// single RP identity represented by the _encryptingCreds field.
        /// </summary>
        /// <param name="principal">The caller's principal</param>
        /// <param name="request">The incoming RST</param>
        /// <returns></returns>
        protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken request)
        {
            // Validate the AppliesTo address
            ValidateAppliesTo( request.AppliesTo );

            // Create the scope using the request AppliesTo address and the RP identity
            Scope scope = new Scope( request.AppliesTo.Uri.AbsoluteUri, _signingCreds );

            if (Uri.IsWellFormedUriString(request.ReplyTo, UriKind.Absolute))
            {
                if (request.AppliesTo.Uri.Host != new Uri(request.ReplyTo).Host)
                    scope.ReplyToAddress = request.AppliesTo.Uri.AbsoluteUri;
                else
                    scope.ReplyToAddress = request.ReplyTo;
            }
            else
            {
                Uri resultUri = null;
                if (Uri.TryCreate(request.AppliesTo.Uri, request.ReplyTo, out resultUri))
                    scope.ReplyToAddress = resultUri.AbsoluteUri;
                else
                    scope.ReplyToAddress = request.AppliesTo.Uri.ToString() ;
            }

            // Note: In this sample app only a single RP identity is shown, which is localhost, and the certificate of that RP is 
            // populated as _encryptingCreds
            // If you have multiple RPs for the STS you would select the certificate that is specific to 
            // the RP that requests the token and then use that for _encryptingCreds
            scope.EncryptingCredentials = _encryptingCreds;

            return scope;
        }
        /// <summary>
        /// This method returns the content of the issued token. The content is represented as a set of
        /// IClaimIdentity intances, each instance corresponds to a single issued token. Currently, the Windows Identity Foundation only
        /// supports a single token issuance, so the returned collection must always contain only a single instance.
        /// </summary>
        /// <param name="scope">The scope that was previously returned by GetScope method</param>
        /// <param name="principal">The caller's principal</param>
        /// <param name="request">The incoming RST, we don't use this in our implementation</param>
        /// <returns></returns>
        protected override ClaimsIdentity GetOutputClaimsIdentity( ClaimsPrincipal principal, RequestSecurityToken request, Scope scope )
        {
            //
            // Return a default claim set which contains a custom decision claim
            // Here you can actually examine the user by looking at the IClaimsPrincipal and 
            // return the right decision based on that. 
            //
            ClaimsIdentity outgoingIdentity = new ClaimsIdentity();
            outgoingIdentity.AddClaims(principal.Claims);

            return outgoingIdentity;
        }
        /// <summary>
        /// Validates the appliesTo and throws an exception if the appliesTo is null or appliesTo contains some unexpected address.
        /// </summary>
        /// <param name="appliesTo">The AppliesTo parameter in the request that came in (RST)</param>
        /// <returns></returns>
        void ValidateAppliesTo(EndpointReference appliesTo)
        {
            if (appliesTo == null)
            {
                throw new InvalidRequestException("The appliesTo is null.");
            }

            if (!appliesTo.Uri.Equals(new Uri(_addressExpected)))
            {
                throw new InvalidRequestException(String.Format("The relying party address is not valid. Expected value is {0}, the actual value is {1}.", _addressExpected, appliesTo.Uri.AbsoluteUri));
            }
        }

    }
}

다음 코드에서는 사용자 지정 수동 STS를 호출하여 파일의 코드 숨김 FederatedPassiveSecurityTokenServiceOperations.ProcessRequest(HttpRequest, ClaimsPrincipal, SecurityTokenService, HttpResponse) 에서 메서드를 호출 default.aspx.cs 하여 WS-Federation 요청을 처리하는 방법을 보여 줍니다.

using System;
using System.IdentityModel.Services;
using System.Security.Claims;

namespace PassiveSTS
{
    public partial class _Default : System.Web.UI.Page
    {
        /// <summary>
        /// We perform the WS-Federation Passive Protocol processing in this method. 
        /// </summary>
        protected void Page_PreRender( object sender, EventArgs e ) 
        {
            FederatedPassiveSecurityTokenServiceOperations.ProcessRequest( Request, User as ClaimsPrincipal, CustomSecurityTokenServiceConfiguration.Current.CreateSecurityTokenService(), Response );
        }
    }
}

설명

STS를 만들려면 클래스에서 SecurityTokenService 파생해야 합니다. 사용자 지정 클래스에서 최소한 해당 및 GetScope 메서드를 재정의 GetOutputClaimsIdentity 해야 합니다. 이러한 재정의를 사용하면 클래스에 정의된 다른 모든 메서드의 기본 구현을 사용하여 만든 STS는 RST(보안 토큰 요청)에 대한 응답으로 보안 토큰을 발급할 수 있습니다. 즉, WS-Trust 사양에 정의된 문제 바인딩이 구현됩니다. 이 바인딩은 메서드에서 Issue 구현됩니다. 다른 WS-Trust 바인딩(갱신, 취소 및 유효성 검사)은 기본 사례에서 구현되지 않으며 이러한 바인딩 중 하나에 해당하는 RST가 발견되면 적절한 오류가 호출자에게 반환됩니다. 물론 적절한 메서드(RenewCancelValidate)를 재정의하여 STS에서 이러한 바인딩을 구현할 수 있습니다.

Important

프로덕션 준비 STS를 구현하려면 이러한 서비스 노출에 내재된 잠재적인 보안 위험을 완화하기 위해 신중한 계획과 상당한 리소스가 필요합니다. WIF(Windows Identity Foundation)를 사용하는 대부분의 개발자는 STS 자체를 개발하는 대신 ID 관리를 STS에 아웃소싱하는 애플리케이션을 개발합니다. WIF는 개발자가 개발 환경에서 솔루션을 테스트할 수 있도록 Visual Studio 확장인 Visual Studio 2012용 ID 및 액세스 도구를 제공합니다. 이 도구에는 개발 중인 애플리케이션에 특정 클레임을 제공하도록 구성할 수 있는 STS LocalSTS가 포함되어 있습니다. ID 및 액세스 도구에 대한 자세한 내용은 2012 참조하세요. 일부 시나리오에서는 애플리케이션을 LocalSTS 적절하게 테스트하는 데 필요한 기능을 제공하지 못할 수 있습니다. 예를 들어 애플리케이션에서 사용할 사용자 지정 토큰 처리기를 개발하는 시나리오를 예로 들 수 있습니다. 이러한 경우 개발 환경에 배포할 수 있고 애플리케이션에서 SecurityTokenService 이러한 기능을 테스트하는 데 사용할 수 있는 하나 이상의 간단한 STS를 만들기 위해 파생될 수 있습니다. 이 섹션의 나머지 부분에서는 간단한 STS를 구현하고 토큰 발급 파이프라인을 확장할 수 있는 클래스에서 노출 SecurityTokenService 하는 메서드에 중점을 둡니다.

다음 목록에서는 테스트 또는 개발 환경에서 사용하기 위해 개발자에게 가장 중요한 방법에 대한 간략한 개요를 제공합니다.

  • GetScope 메서드입니다. 이 메서드는 Scope RP에 대한 정보를 포함하는 개체를 반환합니다. 이 개체는 토큰 발급 파이프라인의 나머지 부분에 사용되며 응답 AppliesToReplyTo 에 사용할 서명 및 암호화 자격 증명과 필요한 경우 주소에 대한 정보를 포함합니다. 이 메서드를 재정의해야 합니다.

  • GetOutputClaimsIdentity 메서드입니다. 이 메서드는 RP로 ClaimsIdentity 반환할 클레임을 포함하는 개체를 반환합니다. 이 메서드를 재정의해야 합니다.

  • Issue 메서드입니다. 이 메서드는 들어오는 RST(보안 토큰 요청)를 처리하고 RP로 인증하는 데 사용할 수 있는 토큰이 포함된 호출자에게 RSTR(응답)을 반환하는 토큰 요청 파이프라인을 구현합니다. 클래스에 SecurityTokenService 정의된 다른 많은 메서드는 이 메서드와 메서드를 GetScopeGetOutputClaimsIdentity 포함하여 이 메서드에서 호출됩니다. 이 메서드를 재정의할 필요는 없지만 구현하는 토큰 요청 파이프라인을 이해하는 것이 유용할 수 있습니다.

STS는 클래스를 통해 구성됩니다 SecurityTokenServiceConfiguration .

구현자 참고

메서드와 메서드를 모두 재정의 GetScope(ClaimsPrincipal, RequestSecurityToken)GetOutputClaimsIdentity(ClaimsPrincipal, RequestSecurityToken, Scope) 해야 합니다.

생성자

Name Description
SecurityTokenService(SecurityTokenServiceConfiguration)

지정된 구성 설정을 사용하여 클래스를 초기화 SecurityTokenService 하기 위해 파생 클래스에서 호출됩니다.

속성

Name Description
Principal

현재 인스턴스와 연결된 보안 주체를 가져오거나 설정합니다.

Request

현재 인스턴스와 연결된 RST(보안 토큰 요청)를 가져오거나 설정합니다.

Scope

현재 인스턴스와 연결된 범위를 가져오거나 설정합니다.

SecurityTokenDescriptor

현재 인스턴스와 연결된 값을 가져오거나 설정합니다 SecurityTokenDescriptor .

SecurityTokenServiceConfiguration

소유자 구성 인스턴스를 가져옵니다.

메서드

Name Description
BeginCancel(ClaimsPrincipal, RequestSecurityToken, AsyncCallback, Object)

파생 클래스에서 재정의되는 경우 비동기 WS-Trust 취소 요청을 시작합니다.

BeginGetOutputClaimsIdentity(ClaimsPrincipal, RequestSecurityToken, Scope, AsyncCallback, Object)

파생 클래스에서 재정의되는 경우 메서드에 대한 비동기 호출을 GetOutputClaimsIdentity(ClaimsPrincipal, RequestSecurityToken, Scope) 시작합니다.

BeginGetScope(ClaimsPrincipal, RequestSecurityToken, AsyncCallback, Object)

파생 클래스에서 재정의되는 경우 메서드에 대한 비동기 호출을 GetScope(ClaimsPrincipal, RequestSecurityToken) 시작합니다.

BeginIssue(ClaimsPrincipal, RequestSecurityToken, AsyncCallback, Object)

파생 클래스에서 재정의되는 경우 비동기 WS-Trust 문제 요청을 시작합니다.

BeginRenew(ClaimsPrincipal, RequestSecurityToken, AsyncCallback, Object)

파생 클래스에서 재정의되는 경우 비동기 WS-Trust 갱신 요청을 시작합니다.

BeginValidate(ClaimsPrincipal, RequestSecurityToken, AsyncCallback, Object)

파생 클래스에서 재정의되는 경우 비동기 WS-Trust 유효성 검사 요청을 시작합니다.

Cancel(ClaimsPrincipal, RequestSecurityToken)

파생 클래스에서 재정의되는 경우 WS-Trust 취소 요청을 처리합니다.

CreateSecurityTokenDescriptor(RequestSecurityToken, Scope)

의 인스턴스를 SecurityTokenDescriptor만듭니다.

EndCancel(IAsyncResult)

파생 클래스에서 재정의된 경우 비동기 WS-Trust 취소 요청을 완료합니다.

EndGetOutputClaimsIdentity(IAsyncResult)

파생 클래스에서 재정의되는 경우 메서드에 대한 비동기 호출을 BeginGetOutputClaimsIdentity(ClaimsPrincipal, RequestSecurityToken, Scope, AsyncCallback, Object) 완료합니다.

EndGetScope(IAsyncResult)

파생 클래스에서 재정의되는 경우 메서드에 대한 비동기 호출을 BeginGetScope(ClaimsPrincipal, RequestSecurityToken, AsyncCallback, Object) 완료합니다.

EndIssue(IAsyncResult)

파생 클래스에서 재정의되는 경우 비동기 WS-Trust 문제 요청을 완료합니다.

EndRenew(IAsyncResult)

파생 클래스에서 재정의된 경우 비동기 WS-Trust 갱신 요청을 완료합니다.

EndValidate(IAsyncResult)

파생 클래스에서 재정의된 경우 비동기 WS-Trust 유효성 검사 요청을 완료합니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 여부를 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 사용됩니다.

(다음에서 상속됨 Object)
GetIssuerName()

STS(보안 토큰 서비스)의 이름을 가져옵니다.

GetOutputClaimsIdentity(ClaimsPrincipal, RequestSecurityToken, Scope)

파생 클래스에서 재정의된 경우 이 메서드는 발급된 토큰에 포함할 출력 주체의 컬렉션을 반환합니다.

GetProofToken(RequestSecurityToken, Scope)

RSTR(응답)에 포함할 증명 토큰을 가져옵니다.

GetRequestorProofEncryptingCredentials(RequestSecurityToken)

요청자의 증명 암호화 자격 증명을 가져옵니다.

GetResponse(RequestSecurityToken, SecurityTokenDescriptor)

지정된 요청(RST) 및 보안 토큰 설명자를 사용하여 발급된 토큰을 포함하는 응답(RSTR)을 만듭니다.

GetScope(ClaimsPrincipal, RequestSecurityToken)

Scope 지정된 요청(RST)과 연결된 RP(신뢰 당사자)에 대한 정보가 들어 있는 개체를 가져옵니다. 클래스 구현에서 이 메서드를 SecurityTokenService 재정의해야 합니다.

GetSecurityTokenHandler(String)

지정된 형식의 보안 토큰을 발급하기 위한 적절한 보안 토큰 처리기를 가져옵니다.

GetTokenLifetime(Lifetime)

발급된 토큰의 수명을 가져옵니다.

GetType()

현재 인스턴스의 Type 가져옵니다.

(다음에서 상속됨 Object)
Issue(ClaimsPrincipal, RequestSecurityToken)

보안 토큰을 발급합니다.

MemberwiseClone()

현재 Object단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
Renew(ClaimsPrincipal, RequestSecurityToken)

파생 클래스에서 재정의되는 경우 WS-Trust 갱신 요청을 처리합니다.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)
Validate(ClaimsPrincipal, RequestSecurityToken)

파생 클래스에서 재정의된 경우 WS-Trust 유효성 검사 요청을 처리합니다.

ValidateRequest(RequestSecurityToken)

이 인스턴스에 의해 캡슐화된 RST(보안 토큰 요청)의 유효성을 검사합니다.

적용 대상

추가 정보