安全wcf(使用用户名密码验证器)不能从php客户端工作


Secure wcf (using username password validator) not working from php client

我在。net c#(框架4.5)中构建了一个简单的安全wcf与wsHttpBinding,并从。net c#(也)客户端消费它,一切都很好。但是当我试图从php(5.5)客户端通过调用wcs服务的方法来消费它时,客户端不工作并且它已经进入无限循环并且没有显示任何错误消息,只是循环

以下是我的wcf ServiceContractOperationContract 's:

namespace CenteralServices
{
    [ServiceContract]
    public interface IAdminServices
    {
        [OperationContract]
        int Add(int x, int y);
    }
}


b。下面是wcf的配置文件Web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <services>
            <service name= "CentralTicketServicesSystem.AdminSystem" 
                behaviorConfiguration="customBehaviour">
                <endpoint address="AdminServices" 
                        binding="wsHttpBinding" 
              contract="CentralTicketServicesSystem.IAdminServices"
              bindingConfiguration="ServiceBinding"
              behaviorConfiguration="MyEndPointBehavior">
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8080/AdminServicesSystem" />
      </baseAddresses>
    </host>
  </service>
</services>
<bindings>
  <wsHttpBinding>
    <binding name="ServiceBinding"
             openTimeout="00:10:00"
             closeTimeout="00:10:00"
             receiveTimeout="00:10:00"
             sendTimeout="00:10:00">
      <security mode="Message" >
        <message clientCredentialType="UserName"/>
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<behaviors>
  <endpointBehaviors>
    <behavior name="MyEndPointBehavior">
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="customBehaviour">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
      <serviceAuthorization principalPermissionMode="Custom">
        <authorizationPolicies>
          <add policyType="CentralServicesHost.AuthorizationPolicy, CentralServicesHost" />
        </authorizationPolicies>
      </serviceAuthorization>
      <serviceCredentials>
        <userNameAuthentication userNamePasswordValidationMode="Custom"
           customUserNamePasswordValidatorType="CentralServicesHost.UserAuthentication, CentralServicesHost"/>
        <serviceCertificate findValue="15 63 10 5e b6 4b 4d 85 4b 2e 4d 5b ec 85 02 ec"
                            storeLocation="LocalMachine"
                            x509FindType="FindBySerialNumber"
                            storeName="My"/>
      </serviceCredentials>
    </behavior>
    <behavior name="mexBehaviour" >
      <serviceMetadata httpGetEnabled="true" />
    </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>



c。以下是UserAuthentication类:

namespace CentralServicesHost
{
    public class UserAuthentication : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName))
                throw new ArgumentNullException("userName");
            if (string.IsNullOrEmpty(password))
                throw new ArgumentNullException("password");
            if (userName != "test" && password != "test")
                 throw new FaultException("Unknown Username or Incorrect Password.");
        }
    }
}



d。以下是AuthorizationPolicy类:

namespace CentralServicesHost
{
    public class AuthorizationPolicy : IAuthorizationPolicy
    {
        Guid _id = Guid.NewGuid();
        // this method gets called after the authentication stage
        public bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {
            // get the authenticated client identity
            IIdentity client = GetClientIdentity(evaluationContext);
            // set the custom principal
            evaluationContext.Properties["Principal"] = new CustomPrincipal(client);
            return true;
        }
        private IIdentity GetClientIdentity(EvaluationContext ec)
        {
            object obj;
            if (!ec.Properties.TryGetValue("Identities", out obj))
                throw new Exception("No Identity found");
            IList<IIdentity> identities = obj as IList<IIdentity>;
            if (identities == null || identities.Count <= 0)
                throw new Exception("No Identity found");
            return identities[0];
        }
        public System.IdentityModel.Claims.ClaimSet Issuer
        {
            get { return ClaimSet.System; }
        }
        public string Id
        {
            get { return _id.ToString(); }
        }
    }
}



e。以下是CustomPrincipal类:

namespace CentralServicesHost
{
    class CustomPrincipal : IPrincipal
    {
        IIdentity _identity;
        string[] _roles;
        public CustomPrincipal(IIdentity identity)
        {
            _identity = identity;
        }
        // helper method for easy access (without casting)
        public static CustomPrincipal Current
        {
            get
            {
                return Thread.CurrentPrincipal as CustomPrincipal;
            }
        }
        public IIdentity Identity
        {
            get { return _identity; }
        }
        // return all roles
        public string[] Roles
        {
            get
            {
                EnsureRoles();
                return _roles;
            }
        }
        // IPrincipal role check
        public bool IsInRole(string role)
        {
            EnsureRoles();
            return (_roles != null) ? _roles.Contains(role) : false;
        }
        // read Role of user from database
        protected virtual void EnsureRoles()
        {
            using (var s = new SupportedMaterialsSystemEntities())
            {
                _roles = new string[1] { "admin" };
            }
        }
    }
}

f。下面是我的php客户端代码:

<?php
$options = array('soap_version' => SOAP_1_2, 
                  'login'      =>  'test',
                  'password'   =>  'test');
$wsdl = "http://localhost:8080/AdminServicesSystem";
$client = new SoapClient($wsdl, $options);
$obj = new stdClass;
$obj->x = 3;
$obj->y = 3;
$retval = $client->Add($obj);//here the browser loops for infinite without any response.
//var_dump($exc);//THIS POINT NOT REACHED
//die();
$result = $retval->AddResult;
echo $result;

指出:
1。我的操作系统是Win. 8.1,我使用的是visual studio 2013(作为管理员)和php Wamp Server。
2。我都试过了,在IIS 6.2和控制台应用程序中托管wcf服务,但它们都没有改变我的php客户端循环。
3。我已经使用IIS管理器创建了自签名证书,并将其存储在我的本地计算机中。
4。当我将php代码中的soap_versionSOAP_1_2更改为SOAP_1_1时,我有Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8'.

去年注意:
我的。net c#客户端代码如下:

 using (var svcProxy = new AdminServiceProxy.AdminServicesSystemClient())
        {
            svcProxy.ClientCredentials.UserName.UserName = "test";
            svcProxy.ClientCredentials.UserName.Password = "test";
            Console.WriteLine(svcProxy.Add(1, 1));//the service works fine and print 2
        }
 }


那么,从php调用安全wcf(使用wsHttpBinding)服务的正确方法是什么呢?

我相信您需要发布一个默认的WSDL元数据来使用PHP soap客户端(参见这里的能力http://php.net/manual/en/intro.soap.php)。

尝试添加带有basicHttpBinding绑定的端点,它可以为您的客户机提供WSDL,然后使用该端点。

在地址http://localhost:8080/AdminServicesSystem上,您有mexHttpBinding端点,它以其他格式(http://www.w3.org/TR/2009/WD-ws-metadata-exchange-20090317/)提供元数据。

尝试在这里查看表单的更多细节:https://abhishekdv.wordpress.com/2013/05/24/mexhttpbinding-vs-wsdl/