5

我正在尝试通过有关 HTTP Authentication Adapter 的 ZF2 文档Zend\Authentication\Adapter\Http中的说明来实现基于 HTTP 的身份验证。

我想阻止每个传入的请求,直到用户代理通过身份验证,但是我不确定如何在我的模块中实现它。

如何设置我的 Zend\Mvc 应用程序以拒绝访问我的控制器?

4

3 回答 3

11

您正在寻找的可能是附加到Zend\Mvc\MvcEvent::EVENT_DISPATCH应用程序事件的侦听器。

为了阻止通过身份验证适配器访问任何操作,您必须执行以下操作。首先,定义一个负责生产您的身份验证适配器的工厂:

namespace MyApp\ServiceFactory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Authentication\Adapter\Http as HttpAdapter;
use Zend\Authentication\Adapter\Http\FileResolver;

class AuthenticationAdapterFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config         = $serviceLocator->get('Config');
        $authConfig     = $config['my_app']['auth_adapter'];
        $authAdapter    = new HttpAdapter($authConfig['config']);
        $basicResolver  = new FileResolver();
        $digestResolver = new FileResolver();

        $basicResolver->setFile($authConfig['basic_passwd_file']);
        $digestResolver->setFile($authConfig['digest_passwd_file']);
        $adapter->setBasicResolver($basicResolver);
        $adapter->setDigestResolver($digestResolver);

        return $adapter;
    }
}

这个工厂基本上会给你一个配置的身份验证适配器,并将它的实例化逻辑抽象掉。

让我们继续并为我们的应用程序的dispatch事件附加一个侦听器,以便我们可以阻止任何具有无效身份验证标头的请求:

namespace MyApp;

use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;
use Zend\EventManager\EventInterface;
use Zend\Mvc\MvcEvent;
use Zend\Http\Request as HttpRequest;
use Zend\Http\Response as HttpResponse;

class MyModule implements ConfigProviderInterface, BootstrapListenerInterface
{
    public function getConfig()
    {
        // moved out for readability on SO, since config is pretty short anyway
        return require __DIR__ . '/config/module.config.php';
    }

    public function onBootstrap(EventInterface $event)
    {
        /* @var $application \Zend\Mvc\ApplicationInterface */
        $application    = $event->getTarget();
        $serviceManager = $application->getServiceManager();

        // delaying instantiation of everything to the latest possible moment
        $application
            ->getEventManager()
            ->attach(function (MvcEvent $event) use ($serviceManager) {
            $request  = $event->getRequest();
            $response = $event->getResponse();

            if ( ! (
                $request instanceof HttpRequest
                && $response instanceof HttpResponse
            )) {
                return; // we're not in HTTP context - CLI application?
            }

            /* @var $authAdapter \Zend\Authentication\Adapter\Http */
            $authAdapter = $serviceManager->get('MyApp\AuthenticationAdapter');

            $authAdapter->setRequest($request);
            $authAdapter->setResponse($response);

            $result = $adapter->authenticate();

            if ($result->isValid()) {
                return; // everything OK
            }

            $response->setBody('Access denied');
            $response->setStatusCode(HttpResponse::STATUS_CODE_401);

            $event->setResult($response); // short-circuit to application end

            return false; // stop event propagation
        }, MvcEvent::EVENT_DISPATCH);
    }
}

然后是模块默认配置,在这种情况下被移动到MyModule/config/module.config.php

return array(
    'my_app' => array(
        'auth_adapter' => array(
            'config' => array(
                'accept_schemes' => 'basic digest',
                'realm'          => 'MyApp Site',
                'digest_domains' => '/my_app /my_site',
                'nonce_timeout'  => 3600,
            ),
            'basic_passwd_file'  => __DIR__ . '/dummy/basic.txt',
            'digest_passwd_file' => __DIR__ . '/dummy/digest.txt',
        ),
    ),
    'service_manager' => array(
        'factories' => array(
            'MyApp\AuthenticationAdapter'
                => 'MyApp\ServiceFactory\AuthenticationAdapterFactory',
        ),
    ),
);

这是你如何完成它的本质。

显然,您需要my_app.auth.local.php在目录中放置类似文件的内容config/autoload/,并使用特定于当前环境的设置(请注意,此文件不应提交给您的 SCM):

<?php
return array(
    'my_app' => array(
        'auth_adapter' => array(
            'basic_passwd_file'  => __DIR__ . '/real/basic_passwd.txt',
            'digest_passwd_file' => __DIR__ . '/real/digest_passwd.txt',
        ),
    ),
);

最后,如果您还想拥有更好的可测试代码,您可能希望将定义为闭包的侦听器移动到实现Zend\EventManager\ListenerAggregateInterface.

您可以使用ZfcUser由 a 支持的Zend\Authentication\Adapter\Http,与 结合来实现相同的结果BjyAuthorize,它处理未授权操作的侦听器逻辑。

于 2013-03-18T01:55:33.387 回答
1

@ocramius的答案是接受答案但是您忘记描述如何编写两个文件basic_password.txtdigest_passwd.txt

根据Zend 2 Official Doc about Basic Http Authentication

  • basic_passwd.txt文件包含用户名、领域(与您的配置相同的领域)和纯密码 -><username>:<realm>:<credentials>\n

  • digest_passwd.txt文件包含用户名、领域(与您的配置相同的领域)和密码散列使用 MD5 散列 -><username>:<realm>:<credentials hashed>\n

例子:

如果basic_passwd.txt文件:

user:MyApp Site:password\n

然后digest_passwd.txt归档:

user:MyApp Site:5f4dcc3b5aa765d61d8327deb882cf99\n
于 2015-09-02T15:58:29.097 回答
0

或者,您可以使用 Apache Resolver for HTTP Adapter

use Zend\Authentication\Adapter\Http\ApacheResolver;

$path = 'data/htpasswd';

// Inject at instantiation:
$resolver = new ApacheResolver($path);

// Or afterwards:
$resolver = new ApacheResolver();
$resolver->setFile($path);

根据 https://zendframework.github.io/zend-authentication/adapter/http/#resolvers

于 2016-08-12T11:05:49.967 回答