1

大家好,我正在尝试学习如何在 PHP 中创建 SOAP Web 服务端点。我发现了 Laminas-soap 及其优雅的解决方案。然而,当尝试向它添加身份验证时,虽然它在向它通过的 SoapHeaders 添加信用时有效,但问题是即使没有 SoapHeaders 凭据,它仍然会通过。有人可以帮我解决这个问题吗?这是我的服务器代码:

更新:我是否应该在每次调用时都进行身份验证以不在服务器上放置状态?

    <?php

// api.php

require_once __DIR__ . '/vendor/autoload.php';
require_once '../classes/DBConnection.php';

class Server
{   
    
    private $conn;
     
    /**
     * authenticate
     *
     * @param  string $username
     * @param  string $password
     * @return boolean
     */
    public static function authenticate($username, $password) 
    {
        if($username == "Kaloy" && $password == 'password') return true;
        else throw new SOAPFault("Wrong user/pass combination", 401);
    }   

    public function __construct($conn) 
    {
        $this->conn = $conn;    
    }

    /**
     * Say hello.
     *
     * @param string $firstName
     * @return string $greetings
     */
    public function sayHello($firstName)
    {
        return 'Hello ' . $firstName;
    }
        
    /**
     * get products
     *
     * @param string $category
     * @param string $category2
     * @param string $category3
     * @param string $category4
     * @return Array $products
     */
    public function getProd($category, $category2, $category3, $category4) {
        if ($category == "books") {
            // return join(",", array(
            //     "The WordPress Anthology",
            //     "PHP Master: Write Cutting Edge Code",
            //     "Build Your Own Website the Right Way"));
            return array(
                "The WordPress Anthology",
                "PHP Master: Write Cutting Edge Code",
                "Build Your Own Website the Right Way");
        }
        else {            
            return array("No products listed under that category");
        }
    }
        
    /**
     * getData
     *
     * @param string $id
     * @return Object
     */
    public function getData($id) 
    {
        $result = [];
        if (is_null($id)) return $result;
        $qry = "SELECT * FROM test_table";
        return $this->conn->query($qry)->fetchAll(PDO::FETCH_ASSOC);
    }

}

$serverUrl = "http://localhost/laminas-soap/api.php";
$options = [
    'uri' => $serverUrl,
];
$server = new \Laminas\Soap\Server(null, $options);

if (isset($_GET['wsdl'])) {
    $soapAutoDiscover = new \Laminas\Soap\AutoDiscover(new \Laminas\Soap\Wsdl\ComplexTypeStrategy\ArrayOfTypeSequence());
    $soapAutoDiscover->setBindingStyle(array('style' => 'document'));
    $soapAutoDiscover->setOperationBodyStyle(array('use' => 'literal'));
    $soapAutoDiscover->setClass('Server');
    $soapAutoDiscover->setUri($serverUrl);
    
    header("Content-Type: text/xml");
    echo $soapAutoDiscover->generate()->toXml();
} else {
    $soap = new \Laminas\Soap\Server($serverUrl . '?wsdl');
    $soap->setObject(new \Laminas\Soap\Server\DocumentLiteralWrapper(new Server($conn)));
    $soap->handle();
}
4

0 回答 0