【问题标题】:Http authentication with ZendZend 的 Http 身份验证
【发布时间】:2012-06-22 10:43:28
【问题描述】:

我想用 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();。有人能找到出路吗?

【问题讨论】:

    标签: php http zend-framework


    【解决方案1】:

    您不必使用文件解析器。您可以编写自己的解析器类,只需扩展 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();
    

    【讨论】:

    • 非常感谢代码示例,可以举个请求结构的例子吗?
    • 您需要了解如何使用您正在使用的特定客户端实现基本身份验证。如果您使用 Zend_Http_Client,stackoverflow.com/questions/9623768/… 可能会有所帮助
    【解决方案2】:

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

        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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 2012-10-27
      • 1970-01-01
      相关资源
      最近更新 更多