WCF身份验证不会提示输入凭据

时间:2012-03-22 10:35:28

标签: c# wcf wcf-security

我已经创建了一个测试WCF应用程序,其中我正在尝试使用身份验证,但它只是运行我的方法而不是要求我登录/验证。下面是我的WCF应用程序中的web.config中的代码片段:

<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>

4 个答案:

答案 0 :(得分:0)

看起来你使用了错误的绑定,客户端在你在服务器上定义WsHttpBinding时使用了BasicHttpBinding。

答案 1 :(得分:0)

WCF / IIS将神奇地连接您拥有的服务而无需配置(无法记住此功能的名称......)。但是,您正在定义一些自定义绑定配置 - 这很好,但您需要告诉您的服务使用它。

您需要在服务器的配置中添加<service>元素,例如:

<system.serviceModel>
   ...
   <services>
      <service name="FullClassNameOfYourService">
         <endpoint binding="wsHttpBinding"
                   bindingConfiguration="Binding1"
                   contract="FullClassNameOfYourServiceContract" />
      </service>
   </services>

此外,您的客户端配置不包含wsHttpBinding元素的事实表明,未为托管您服务的网站启用HTTPS。

答案 2 :(得分:0)

您的userName身份验证不正确。 customUserNamePasswordValidatorType的格式必须为“[full qualified assembly + classname],[namespace]”。我不知道你的帖子中你的命名空间是什么,但是像:

<userNameAuthentication userNamePasswordValidationMode="Custom"
 customUserNamePasswordValidatorType="MyNamespace.Authorization , MyNamespace" />

正如其他人所说,您的客户端必须使用相同的绑定类型才能连接到该服务。

此外,在服务器端,您已将安全模式设置为无,但您有传输和消息标记。在安全标记内。如果您将None作为安全性,则忽略任何传输和消息安全性规范。换句话说,如果安全模式为None,则会忽略您的客户端凭据类型,因此客户端无需进行身份验证。

答案 3 :(得分:0)

您使用具有简化配置文件的WCF 4。它有其优点,但调试起来比较困难。我怀疑你的自定义wshttpbinding没有应用。尝试更详细的配置(如wcf 3.5):

<system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="NewBinding0">
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="WcfService6.Service1Behavior"
        name="WcfService6.Service1">
        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="NewBinding0"
          contract="WcfService6.IService1">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfService6.Service1Behavior">
          <!-- 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>
  </system.serviceModel>