Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blocking access via HTTP Authentication with Zend Framework 2

I'm trying to implement HTTP-based authentication through a Zend\Authentication\Adapter\Http as explained in the ZF2 documentation about the HTTP Authentication Adapter.

I want to block every incoming request until the user agent is authenticated, however I'm unsure about how to implement this in my module.

How would I setup my Zend\Mvc application to deny access to my controllers?

like image 777
Matt Avatar asked Mar 17 '13 22:03

Matt


2 Answers

What you are looking for is probably a listener attached to the Zend\Mvc\MvcEvent::EVENT_DISPATCH event of your application.

In order, here's what you have to do to block access to any action through an authentication adapter. First of all, define a factory that is responsible for producing your authentication adapter:

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;
    }
}

This factory will basically give you a configured auth adapter, and abstract its instantiation logic away.

Let's move on and attach a listener to our application's dispatch event so that we can block any request with invalid authentication headers:

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);
    }
}

And then the module default configuration, which in this case was moved to 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',
        ),
    ),
);

This is the essence of how you can get it done.

Obviously, you need to place something like an my_app.auth.local.php file in your config/autoload/ directory, with the settings specific to your current environment (please note that this file should NOT be committed to your 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',
        ),
    ),
);

Eventually, if you also want to have better testable code, you may want to move the listener defined as a closure to an own class implementing the Zend\EventManager\ListenerAggregateInterface.

You can achieve the same results by using ZfcUser backed by a Zend\Authentication\Adapter\Http, combined with BjyAuthorize, which handles the listener logic on unauthorized actions.

like image 55
Ocramius Avatar answered Sep 29 '22 23:09

Ocramius


Answer of @ocramius is accept answer But you forget to describe How to write two files basic_password.txt and digest_passwd.txt

According to Zend 2 Official Doc about Basic Http Authentication:

  • basic_passwd.txt file contains username, realm(the same realm into your configuration) and plain password -> <username>:<realm>:<credentials>\n

  • digest_passwd.txt file contains username, realm(the same realm into your configuration) and password hashing Using MD5 hash -> <username>:<realm>:<credentials hashed>\n

Example:

if basic_passwd.txt file:

user:MyApp Site:password\n

Then digest_passwd.txt file:

user:MyApp Site:5f4dcc3b5aa765d61d8327deb882cf99\n
like image 42
ahmed hamdy Avatar answered Sep 29 '22 23:09

ahmed hamdy