Как мога да накарам моето конзолно приложение да се свърже с IIS хоствана WCF услуга, когато основното и/или Windows удостоверяване е включено и анонимното удостоверяване е изключено?
Сайтът е вътрешен и не се изисква строга сигурност. Няма домейн контролер. Трябва обаче да изключа анонимния достъп.
Търсих с дни и изпробвах много методи, включително използване на самостоятелно хостван сертификат и замяна на валидирането на сертификата, замяна на UserNameValidator
и използване на client.ClientCredentials.Windows.ClientCredentials.UserName
или client.ClientCredentials.UserName.UserName
. Нито едно от тях не е проработило.
Намирам се в момент, в който би било хубаво някой да бъде така любезен да погледне и изпълни кода и да ми помогне да стартирам пробата с удостоверяване.
Позволих си да кача пясъчна среда, съдържаща HostWebSite, ClientConsole и API проекти.
Хостих zip файла на моя Windows Live SkyDrive: WCF_Authentication.zip
Някои малки стъпки за настройка.
Добавих към файла hosts
127.0.0.1 hostwebsite.local
Добавих уебсайт към IIS
-- местоположение:HostWebSite project root
,
-- обвързване:hostwebsite.local
-- набор от приложения:Classic 4.0 app pool
.Приложена сигурност
Everyone
достъп за четене до директорията на проекта HostWebSite.Потвърдете, че можете да видите услугата
http://hostwebsite.local/services/EchoService.svc
Уверете се, че конзолата ехото връща здравей свят.
След това изключете анонимното чрез IIS / Удостоверяване и включете основно и/или Windows удостоверяване.
Благодаря ви
В полза на читателите тук съм включил кодови фрагменти
Проект: API
namespace API.Contract
{
[ServiceContract]
public interface IEcho
{
[OperationContract]
string SendEcho(string message);
}
}
namespace API.Proxy
{
public class EchoProxy : IEcho
{
public string SendEcho(string message)
{
return string.Concat("You said: ", message);
}
}
}
namespace API.Service
{
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public class EchoService : System.ServiceModel.ClientBase<IEcho>, IEcho
{
public EchoService()
{
}
public EchoService(string endpointConfigurationName) :
base(endpointConfigurationName)
{
}
public EchoService(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{
}
public EchoService(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{
}
public EchoService(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress)
{
}
public string SendEcho(string message)
{
return base.Channel.SendEcho(message);
}
}
}
Проект: ClientConsole
static void Main(string[] args)
{
EchoService client = new EchoService("WSHttpBinding_IEcho");
try
{
Console.WriteLine(client.SendEcho("Hello World"));
client.Close(); // i tried putting this in the finally block but the client would close in an errored state it said.
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Клиентска конфигурация
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IEcho" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://hostwebsite.local/Services/EchoService.svc/services/EchoService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IEcho"
contract="API.Contract.IEcho" name="WSHttpBinding_IEcho">
<identity>
<servicePrincipalName value="host/mikev-ws" />
</identity>
</endpoint>
</client>
</system.serviceModel>
Проект: HostWebSite
<system.serviceModel>
<!-- SERVER -->
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceTypeBehaviors">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="API.Proxy.EchoProxy" behaviorConfiguration="MyServiceTypeBehaviors">
<endpoint address="/services/EchoService.svc" binding="wsHttpBinding" contract="API.Contract.IEcho" />
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>