语言

SecurityTokenService 类

定义

定义安全令牌服务(STS)的属性和方法的抽象基类。

public ref class SecurityTokenService abstract
public abstract class SecurityTokenService
type SecurityTokenService = class
Public MustInherit Class SecurityTokenService
继承
SecurityTokenService

示例

主题中使用的 SecurityTokenService 代码示例取自 Custom Token 示例。 此示例提供允许处理简单 Web 令牌(SWT)的自定义类,并包括能够提供 SWT 令牌的被动 STS 的实现。 有关如何实现活动 STS 的示例,可以查看 Federation Metadata 示例。 有关这些示例以及可用于 WIF 的其他示例以及下载位置的信息,请参阅 WIF 代码示例索引。 以下代码演示了使用 SecurityTokenService 类实现被动 STS。

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));
            }
        }

    }
}

以下代码演示如何通过从文件中的代码FederatedPassiveSecurityTokenServiceOperations.ProcessRequest(HttpRequest, ClaimsPrincipal, SecurityTokenService, HttpResponse)调用default.aspx.cs方法来调用自定义被动 STS 来处理 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 需要仔细规划和大量资源,以缓解暴露此类服务时固有的潜在安全风险。 大多数使用 Windows Identity Foundation (WIF) 的开发人员将开发将标识管理外包给 STS 的应用程序,而不是开发 STS 本身。 WIF 提供一个Visual Studio扩展(用于 Visual Studio 2012 的标识和访问工具)来帮助开发人员在开发环境中测试解决方案。 此工具包括 STS, LocalSTS可以配置为向正在开发的应用程序提供特定声明。 有关标识和访问工具的详细信息,请参阅 2012。 在某些情况下, LocalSTS 可能无法提供充分测试应用程序所需的功能;例如,在涉及开发供应用程序使用的自定义令牌处理程序的方案中。 在这些情况下,可以派生自 SecurityTokenService 创建一个或多个可在开发环境中部署的简单 STS,并可用于在应用程序中测试此类功能。 本部分的其余部分重点介绍类公开 SecurityTokenService 的方法,这些方法使你能够实现简单的 STS 并扩展令牌颁发管道。

以下列表简要概述了开发人员在测试或开发环境中使用的主要重要性的方法。

  • GetScope 方法。 此方法返回一个 Scope 对象,该对象包含有关 RP 的信息。 此对象在令牌颁发管道的其余部分使用,包括有关要在响应中使用的签名和加密凭据的信息,以及 AppliesTo 以及( ReplyTo 如果需要)地址的信息。 必须重写此方法。

  • GetOutputClaimsIdentity 方法。 此方法返回一个 ClaimsIdentity 对象,该对象包含要返回到 RP 的声明。 必须重写此方法。

  • Issue 方法。 此方法实现令牌请求管道,该管道处理传入的安全令牌请求(RST),并向调用方返回响应(RSTR),该调用方包含可用于通过 RP 进行身份验证的令牌。 从此方法调用类中 SecurityTokenService 定义的许多其他方法,包括 GetScope 和 GetOutputClaimsIdentity 方法。 无需重写此方法,但了解它实现的令牌请求管道可能会有所帮助。

STS 通过 SecurityTokenServiceConfiguration 类进行配置。

实施者说明

必须同时重写 GetScope(ClaimsPrincipal, RequestSecurityToken) 和 GetOutputClaimsIdentity(ClaimsPrincipal, RequestSecurityToken, Scope) 方法。

构造函数

名称 说明
SecurityTokenService(SecurityTokenServiceConfiguration)

从派生类调用,以使用指定的配置设置初始化 SecurityTokenService 类。

属性

名称 说明
Principal

获取或设置与当前实例关联的主体。

Request

获取或设置与当前实例关联的安全令牌请求(RST)。

Scope

获取或设置与当前实例关联的作用域。

SecurityTokenDescriptor

获取或设置与 SecurityTokenDescriptor 当前实例关联的值。

SecurityTokenServiceConfiguration

获取所有者配置实例。

方法

名称 说明
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 Cancel 请求。

CreateSecurityTokenDescriptor(RequestSecurityToken, Scope)

创建 . 的 SecurityTokenDescriptor实例。

EndCancel(IAsyncResult)

在派生类中重写时,完成异步 WS-Trust Cancel 请求。

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 Renew 请求。

ToString()

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

(继承自 Object)
Validate(ClaimsPrincipal, RequestSecurityToken)

在派生类中重写时,处理 WS-Trust 验证请求。

ValidateRequest(RequestSecurityToken)

验证此实例封装的安全令牌请求(RST)。

适用于

另请参阅