使用 Zend 进行 http 身份验证


Http authentication with Zend

我想用 zend 做一个 http 身份验证,我读了那篇文章 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();。有人能指明出路吗?

您不必使用文件解析程序。您可以通过简单地扩展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();
示例操作

控制器:

    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