stc
stc

Reputation: 1

Zend 2.2 trouble for HTTP Authentication

I try to make an http authentication for one of my module using Zend framework 2.2, my code is strongly inspired from the official documentation, in there is :

    $request=$this->getRequest();
    $response=$this->getResponse();

    assert($request instanceof Zend\Http\Request);
    assert($response instanceof Zend\Http\Response);

The problem is that the assertion goes false, it seems that $request and $response come from another class, so my script's not working. How could I get request and response From Zend\Http\Request|Response in my Controller ?

Many thanks.

Upvotes: 0

Views: 79

Answers (1)

Tounu
Tounu

Reputation: 563

If you want to set an HTTP auth for an entire module, here's what to do (at least how I did it) :

In Module.php :

    public function onBootstrap(MvcEvent $e){
        $sharedEvents=$e->getApplication()->getEventManager()->getSharedManager();
        $sharedEvents->attach(__NAMESPACE__,MvcEvent::EVENT_DISPATCH, array($this, 'authHttp'));
    }


    public function authHttp(MvcEvent $e){

        $serviceManager = $e->getApplication()->getServiceManager();

        $request=$e->getRequest();
        $response=$e->getResponse();

        if(!(
          $request instanceof \Zend\Http\Request
          && $response instanceof \Zend\Http\Response
          )){
          return; // we're not in HTTP context - CLI application?
          } 

        // Your adapter with config/password etc...
        $authAdapter=$serviceManager->get('Admin\AuthenticationAdapter');

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

        $result=$authAdapter->authenticate();

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

        $response->setContent('Access denied');
        $response->setStatusCode(\Zend\Http\Response::STATUS_CODE_401);

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

        return false;
    }

That's all :). This will work for any page of the module !

Upvotes: 1

Related Questions