使用Zend Framework 2通过HTTP身份验证阻止访问

Mat*_*att 5 authentication zend-framework2

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

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

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

Ocr*_*ius 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这个工厂基本上会给你一个配置的auth适配器,并抽象它的实例化逻辑.

让我们继续并将监听器附加到我们的应用程序的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后是模块默认配置,在这种情况下移动到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',
        ),
    ),
);
Run Code Online (Sandbox Code Playgroud)

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

显然,您需要my_app.auth.local.phpconfig/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',
        ),
    ),
);
Run Code Online (Sandbox Code Playgroud)

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

您可以通过使用ZfcUsera的Zend\Authentication\Adapter\Http结合来实现相同的结果,结合使用BjyAuthorize,处理未授权操作的侦听器逻辑.