0

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.

1
  • possible due to not having a leading slash? try \Zend\Http\Request
    – Andrew
    Commented Jul 17, 2013 at 15:48

1 Answer 1

1

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 !

1
  • Don't forget to validate the answer if it was the solution ;). Glad it helped :).
    – Tounu
    Commented Jul 18, 2013 at 7:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.