Я создал тестовое приложение WCF, в котором я пытаюсь заставить Authentication работать, но он просто запускает мой метод и не просит меня войти/пройти проверку подлинности. Ниже фрагменты кода в моем web.config в моем WCF приложения:WCF Аутентификация не запрашивает учетные данные
<bindings>
<wsHttpBinding>
<binding name="Binding1">
<security mode="Message">
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyAPI.Authorization, App_Code" />
</serviceCredentials>
Мой класс Авторизация:
public class Authorization : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (null == userName || null == password)
{
throw new ArgumentNullException();
}
if (!(userName == "test1" && password == "1tset") && !(userName == "test2" && password == "2tset"))
{
// This throws an informative fault to the client.
throw new FaultException("Unknown Username or Incorrect Password");
// When you do not want to throw an infomative fault to the client,
// throw the following exception.
// throw new SecurityTokenException("Unknown Username or Incorrect Password");
}
}
}
Мои Service.svc.cs Класс
public string Hello(string message)
{
return "You typed: " + message;
}
я должен поместите некоторый атрибут выше этого метода, чтобы требовать аутентификации или выше класса?
Я тогда создал тестовое приложение консоли, вот код:
public static Test.Service1Client client = new Test.Service1Client();
static void Main(string[] args)
{
Console.WriteLine(client.Hello("hello"));
Console.ReadLine();
}
Это просто выводит «Введено: привет» без запроса аутентификации. Вот отрывки из моего app.config:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://MyServer/Service1.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService1" contract="Test.IService1"
name="BasicHttpBinding_IService1" />
</client>
</system.serviceModel>
Я бы ожидать, чтобы установить учетные данные для входа перед вызовом client.Hello("hello")
, выполнив:
client.ClientCredentials.UserName.UserName = "test1";
client.ClientCredentials.UserName.Password = "1tset";
Но, очевидно, не
Редактировать<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="Binding1">
<security mode="Message">
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyAPI.Authorization, App_Code" />
</serviceCredentials>
<!-- 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. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Обычно клиент, такой как браузер, запрашивает учетные данные. Ваше тестовое консольное приложение не будет запрашивать, потому что вы не закодировали его таким образом. Сказано, что вызов службы должен был сбой, если вы не предоставили учетные данные. Проверьте, связали ли вы службу с ожиданием Binding1 в конфигурации сервера. – VinayC
@VinayC - Где я вижу это? См. Мое редактирование, он содержит весь мой файл web.config из моей службы. – CallumVass