SecurityTokenService 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
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가 발견되면 적절한 오류가 호출자에게 반환됩니다. 물론 적절한 메서드(RenewCancel및Validate)를 재정의하여 STS에서 이러한 바인딩을 구현할 수 있습니다.
Important
프로덕션 준비 STS를 구현하려면 이러한 서비스 노출에 내재된 잠재적인 보안 위험을 완화하기 위해 신중한 계획과 상당한 리소스가 필요합니다. WIF(Windows Identity Foundation)를 사용하는 대부분의 개발자는 STS 자체를 개발하는 대신 ID 관리를 STS에 아웃소싱하는 애플리케이션을 개발합니다. WIF는 개발자가 개발 환경에서 솔루션을 테스트할 수 있도록 Visual Studio 확장인 Visual Studio 2012용 ID 및 액세스 도구를 제공합니다. 이 도구에는 개발 중인 애플리케이션에 특정 클레임을 제공하도록 구성할 수 있는 STS LocalSTS가 포함되어 있습니다. ID 및 액세스 도구에 대한 자세한 내용은 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 |
소유자 구성 인스턴스를 가져옵니다. |