3

我想用 zend 做一个 http auth,我读了那篇文章http://framework.zend.com/manual/en/zend.auth.adapter.http.html但我不认为它有价值(为什么密码是取自外部文件...?)。我知道它可以简单地用标题来完成:

header('WWW-Authenticate: Basic realm=sdfsdf');
header('HTTP/1.0 401 Unauthorized');
die;

但由于我们使用的是 Zend,我想转换它:

$response->setHeader('WWW-Authenticate', 'Basic realm="asda"', true);
$response->setHeader('Status', '401 Unauthorized', true);

它不会接受它,没有任何反应。即使它有效,我也不能die();在此之后立即使用。有人能指出出路吗?

4

2 回答 2

4

您不必使用文件解析器。您可以编写自己的解析器类,只需扩展 Zend_Auth_Adapter_Http_Resolver_Interface:

class MyOwnResolver implements Zend_Auth_Adapter_Http_Resolver_Interface
{
    /**
     * Resolve username/realm to password/hash/etc.
     *
     * @param  string $username Username
     * @param  string $realm    Authentication Realm
     * @return string|false User's shared secret, if the user is found in the
     *         realm, false otherwise.
     */
    public function resolve($username, $realm)
    {
        if ($username == 'testUser' && $realm == 'testPassword') {
            return $realm;
        } else {
            return false;
        }
    }
}

/* In your controller */

$config = array(
    'accept_schemes' => 'basic',
    'realm'          => 'My Realm',
    'nonce_timeout'  => 3600,
);
$adapter = new Zend_Auth_Adapter_Http($config);
$result = $adapter->setBasicResolver(new MyOwnResolver())
        ->setRequest($this->getRequest())
        ->setResponse($this->getResponse())
        ->authenticate();
于 2012-06-22T22:01:45.730 回答
0

带有示例动作控制器的示例:

    public function preDispatch() {

        if (
            !isset($_SERVER['PHP_AUTH_USER']) 
            || !isset($_SERVER['PHP_AUTH_PW']) 
            || 'admin' != $_SERVER['PHP_AUTH_USER'] 
            || 'admin' != $_SERVER['PHP_AUTH_PW']
        ) {
            $this->getResponse()->setHeader('WWW-Authenticate', 'Basic realm="Authentication required"');
            $this->getResponse()->setHttpResponseCode(401);
            if ('not-auth' !== $this->getRequest()->getActionName()) {
                $this->_forward('not-auth');
            }
        }
    }

    public function indexAction() { }

    public function notAuthAction() { }

}

在这里找到了这个聪明的解决方案。 https://gist.github.com/umpirsky/1148691

于 2014-07-25T19:41:00.550 回答