如何以编程方式在 WCF 服务上启用 WIF

Windows® Identity Foundation (WIF) 提供与 Windows Communication Foundation (WCF) 的轻松集成。 这样,WCF 服务可使用 WIF 的功能,例如新建声明模型、支持附加安全令牌类型 (SAML 2.0) 以及令牌处理。 本主题说明如何进行此操作。

在自行托管的 WCF 服务中启用 Windows Identity Foundation

  1. 在 Visual Studio 中,将对 WIF 程序集 (Microsoft.IdentityModel.dll) 的引用添加到 WCF 服务项目中。

  2. 添加代码以调用 ConfigureServiceHost 方法,并向其传递要启用 WIF 的服务主机实例。 此操作必须在对该实例调用 ServiceHost.Open() 之前完成。 此方法对 ServiceHost 实例设置进行必要更改,以将 WIF 的功能与 WCF 消息处理管道集成。

    备注

    只有完成 ServiceHost 的所有配置后,才能调用 ConfigureServiceHost。 例如,如果在调用 ConfigureServiceHost 后更新 ServiceHost.Credentials 上的服务证书,则不会在 SecurityTokenHandler 中反映更新。

下面的代码示例说明如何执行此操作:

using (ServiceHost host = new ServiceHost(typeof(ClaimsAwareWebService), new Uri("https://localhost:6020/ClaimsAwareWebService"))) { // Configure WIF on the service host. // This attempts to read the web.config/app.config file and load any // settings from the <Microsoft.IdentityModel> configuration section. FederatedServiceCredentials.ConfigureServiceHost(host);

     host.Open();

     Console.WriteLine(“Service is ready, press ENTER to close ...”); Console.ReadLine();

     host.Close() }

在 Web 托管的 WCF 服务中启用 Windows Identity Foundation

可通过进行以下配置更改,将 Web 托管的服务配置为使用 WIF:

  • 添加 <behaviorConfiguration>(如果不存在):

    <service name="Service" behaviorConfiguration="ClaimsBehavior"> ... </service>
    
  • 在配置中引用行为:

    <behaviors> <serviceBehaviors> <behavior name="ClaimsBehavior" > <!-- Behavior extension to make the service claims aware --> <federatedServiceHostConfiguration/> </behavior> </serviceBehaviors> </behaviors>
    
  • 将行为定义为扩展:

    <extensions> <behaviorExtensions> <!-- This behavior extension will enable the service host to be Claims aware --> <add name="federatedServiceHostConfiguration" type="Microsoft.IdentityModel.Configuration.ConfigureServiceHostBehaviorExtensionElement, Microsoft.IdentityModel, Version=0.6.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> </behaviorExtensions> </extensions>