Настройка WCF-сервиса, защищенного встроенной windows-аутентификацией и подключение к нему
Развертывание WCF-сервиса в корпоративной среде для решения задач интеграции довольно стандартная задача. Это может быть, например, сервис, который предоставляет
API для работы с некоторой системой.
Такой WCF-сервис можно развернуть на отдельном сайте, защищенном встроенной (integrated) windows-аутентификацией.
Для корректной работы такого сервиса необходимо выполнить несколько настроек в файле web.config приложения.
1. В секции <system.web> необходимо указать <authentication mode="Windows" />
2. Секция <system.serviceModel> должна быть отредактирована, в соответствии с примером ниже:
<system.serviceModel>
<services>
<service name="PortalTestingService.TestingService" behaviorConfiguration="PortalTestingServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="" binding="basicHttpBinding" contract="PortalTestingService.IService" bindingConfiguration="TestingBinding">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="TestingBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="PortalTestingServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
В приведенном фрагменте файла web.config нужно обратить внимание на секцию <endpoint>, где указаны атрибуты binding и bindingConfiguration.
Значение атрибута bindingConfiguration ссылается на секцию binding внутри basicHttpBinding. А в секции binding должен быть указан параметр <transport clientCredentialType="Windows" />
Как пример для подключения к WCF-сервису, защищенному встроенной windows-аутентификацией, из клиента на .NET 3.5, можно использовать следующий код (предварительно добавив ссылку на сервис):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.ComponentModel;
using System.ServiceModel;
using System.Security;
namespace PortalTestingApp
{
class Program
{
static void Main(string[] args)
{
BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
EndpointAddress endpoint = new EndpointAddress("http://servername/TestingService.svc");
ServiceReference1.ServiceClient client = new PortalTestingApp.ServiceReference1.ServiceClient(basicHttpBinding, endpoint);
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//client.ChannelFactory.Credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
client.ChannelFactory.Credentials.Windows.ClientCredential.UserName = "username";
client.ChannelFactory.Credentials.Windows.ClientCredential.Password = "userpassword";
client.ChannelFactory.Credentials.Windows.ClientCredential.Domain = "DOMAINNAME";
client.TestMethod(1);
}
}
}
|