Example #1
0
 public function onAuthenticationPost(MvcAuthEvent $e)
 {
     if ($this->container->has('api-identity')) {
         return;
     }
     $this->container->setService('api-identity', $e->getIdentity());
 }
 /**
  * @param MvcAuthEvent $mvcAuthEvent
  *
  * @return null|Identity\IdentityInterface
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     $mvcEvent = $mvcAuthEvent->getMvcEvent();
     $request = $mvcEvent->getRequest();
     if (!$request instanceof HttpRequest) {
         return;
     }
     if (in_array($request->getMethod(), $this->methodsWithoutHash)) {
         return;
     }
     $response = $mvcEvent->getResponse();
     $adapter = $this->getAdapter();
     // configure tokenServer
     $tokenServer = $this->getTokenServer();
     $tokenServer->setAdapter($adapter);
     $tokenServer->setRequest($request);
     $tokenServer->setResponse($response);
     try {
         if ($tokenServer->authenticate()) {
             // Use given identity
             $user = $tokenServer->getUserId();
             if ($user instanceof Identity\IdentityInterface) {
                 return $user;
             }
             // Create identity
             $identity = new Identity\AuthenticatedIdentity($user);
             $identity->setName($user);
             return $identity;
         }
     } catch (TokenException $e) {
         // let's make it a guest
     }
     return new Identity\GuestIdentity();
 }
Example #3
0
 public function onAuthorization(\ZF\MvcAuth\MvcAuthEvent $e)
 {
     // For testing purpose we must reset the autorization to not authorized,
     // otherwise it would entirely skip the authaurisation step. But there should
     // be no side-effect for production
     $e->setIsAuthorized(false);
 }
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     /** @var AclAuthorization $authorization */
     $authorization = $mvcAuthEvent->getAuthorizationService();
     $authenticaton = $mvcAuthEvent->getAuthenticationService();
     /**
      * Regardless of how our configuration is currently through via the Apigility UI,
      * we want to ensure that the default rule for the service we want to give access
      * to a particular identity has a DENY BY DEFAULT rule.
      *
      * Naturally, if you have many versions, or many methods, you would want to build
      * some kind of logic to build all the possible strings, and push these into the
      * ACL. If this gets too cumbersome, writing an assertion would be the next best
      * approach.
      */
     $authorization->deny(null, 'DbApi\\V1\\Rest\\User\\Controller::collection', 'GET');
     $authorization->deny(null, 'DbApi\\V1\\Rest\\User\\Controller::entity', 'GET');
     if ($authenticaton->hasIdentity() && $authenticaton->getIdentity()->getAuthenticationIdentity()) {
         /** @var \ZF\MvcAuth\Identity\IdentityInterface $currentUser */
         $currentUser = $authenticaton->getIdentity()->getAuthenticationIdentity();
         /**
          * Now, add the name of the identity in question as a role to the ACL
          */
         $authorization->addRole($currentUser['user_id']);
         /**
          * Next, assign the particular privilege that this identity needs.
          */
         $authorization->allow($currentUser['user_id'], 'DbApi\\V1\\Rest\\User\\Controller::entity', 'GET');
     }
 }
Example #5
0
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     $identity = $mvcAuthEvent->getIdentity()->getAuthenticationIdentity();
     if (!is_null($identity)) {
         $identity = $this->services->get('User\\Service\\UserService')->fetch($identity['user_id']);
         $this->services->get('Application\\Authorization\\IdentityService')->setIdentity($identity);
     }
 }
 /**
  * @param MvcAuthEvent $mvcAuthEvent
  * @param EventManagerInterface $events
  * @param AuthenticationService $authentication
  */
 public function __construct(MvcAuthEvent $mvcAuthEvent, EventManagerInterface $events, AuthenticationService $authentication)
 {
     $this->attach($events);
     $mvcAuthEvent->setTarget($this);
     $this->mvcAuthEvent = $mvcAuthEvent;
     $this->events = $events;
     $this->authentication = $authentication;
 }
Example #7
0
 /**
  * Authenticate against an API token sent in request headers
  *
  * @param MvcAuthEvent $event
  * @return AuthenticatedIdentity|GuestIdentity
  */
 public function authenticate(MvcAuthEvent $event)
 {
     $header = $event->getMvcEvent()->getRequest()->getHeaders()->get('Api-Key');
     $token = $this->getConfig()['api']['token'];
     if (!$header || $header->getFieldValue() !== $token) {
         return new GuestIdentity();
     }
     return new AuthenticatedIdentity('admin');
 }
 /**
  * Determine if we have an authorization failure, and, if so, return a 403 response
  *
  * @param MvcAuthEvent $mvcAuthEvent
  * @return null|ApiProblemResponse
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     if ($mvcAuthEvent->isAuthorized()) {
         return;
     }
     $response = new ApiProblemResponse(new ApiProblem(403, 'Forbidden'));
     $mvcEvent = $mvcAuthEvent->getMvcEvent();
     $mvcEvent->setResponse($response);
     return $response;
 }
 /**
  * Attempt to determine the authorization resource based on the request
  *
  * Looks at the matched controller.
  *
  * If the controller is in the list of rest controllers, determines if we
  * have a collection or a resource, based on the presence of the named
  * identifier in the route matches or query string.
  *
  * Otherwise, looks for the presence of an "action" parameter in the route
  * matches.
  *
  * Once created, it is injected into the $mvcAuthEvent.
  *
  * @param MvcAuthEvent $mvcAuthEvent
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     $mvcEvent = $mvcAuthEvent->getMvcEvent();
     $request = $mvcEvent->getRequest();
     $routeMatch = $mvcEvent->getRouteMatch();
     $resource = $this->buildResourceString($routeMatch, $request);
     if (!$resource) {
         return;
     }
     $mvcAuthEvent->setResource($resource);
 }
 /**
  * @covers ZF\Apigility\MvcAuth\UnauthorizedListener::__invoke
  */
 public function testInvokePropagates403ResponseWhenAuthorizationHasFailed()
 {
     $unauthorizedListener = new UnauthorizedListener();
     $mvcEvent = new MvcEvent();
     $mvcEvent->setResponse(new Response());
     $mvcAuthEvent = new MvcAuthEvent($mvcEvent, null, null);
     $mvcAuthEvent->setIsAuthorized(false);
     $invokeResponse = $unauthorizedListener->__invoke($mvcAuthEvent);
     $this->assertInstanceOf('ZF\\ApiProblem\\ApiProblemResponse', $invokeResponse);
     $this->assertEquals(403, $invokeResponse->getStatusCode());
     $this->assertEquals('Forbidden', $invokeResponse->getReasonPhrase());
 }
 /**
  *
  * @param MvcAuthEvent $mvcAuthEvent
  * @throws \Dws\Exception\Service\ModelNotFoundException
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     // Add validated identity to ZfcUser storage
     $identity = $mvcAuthEvent->getIdentity();
     if ($identity instanceof AuthenticatedIdentity) {
         $user = $this->userService->getUserMapper()->findById($identity->getAuthenticationIdentity()['user_id']);
         if ($user) {
             $this->authenticationService->getStorage()->write($user);
         }
         $identity->setName(implode(', ', $user->getRoles()->toArray()));
     }
 }
 /**
  * Determine if we have an authentication failure, and, if so, return a 401 response
  *
  * @param MvcAuthEvent $mvcAuthEvent
  * @return null|ApiProblemResponse
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     if (!$mvcAuthEvent->hasAuthenticationResult()) {
         return;
     }
     $authResult = $mvcAuthEvent->getAuthenticationResult();
     if ($authResult->isValid()) {
         return;
     }
     $mvcEvent = $mvcAuthEvent->getMvcEvent();
     $response = new ApiProblemResponse(new ApiProblem(401, 'Unauthorized'));
     $mvcEvent->setResponse($response);
     return $response;
 }
 /**
  * Attempt to authorize the discovered identity based on the ACLs present
  *
  * @param MvcAuthEvent $mvcAuthEvent
  * @void
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     try {
         $requestedImage = $this->getServiceLocator()->get('image.requested.image');
     } catch (ServiceNotCreatedException $e) {
         // service not created caused by service return null (image not found in database)
         return $mvcAuthEvent->getMvcEvent()->getResponse()->setStatusCode(404)->send();
     }
     $authenticatedUser = $this->getServiceLocator()->get('image.authenticated.user');
     // check if requested image owned by authenticated user
     if ($requestedImage->getId() !== null && $requestedImage->getUser()->getId() != $authenticatedUser->getId()) {
         $mvcAuthEvent->setIsAuthorized(false);
     }
 }
 /**
  * Determine if we have an authorization failure, and, if so, return a 403 response
  *
  * @param MvcAuthEvent $mvcAuthEvent
  * @return null|ApiProblemResponse
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     if ($mvcAuthEvent->isAuthorized()) {
         return;
     }
     $mvcEvent = $mvcAuthEvent->getMvcEvent();
     $mvcResponse = $mvcEvent->getResponse();
     // If we have already an ApiProblemResponse, return immediately
     if ($mvcResponse instanceof ApiProblemResponse) {
         return $mvcResponse;
     }
     $response = new ApiProblemResponse(new ApiProblem(403, 'Forbidden'));
     $mvcEvent->setResponse($response);
     return $response;
 }
Example #15
0
    /**
     * @param MvcAuthEvent $mvcAuthEvent
     * @throws \Dws\Exception\Service\ModelNotFoundException
     */
    public function __invoke(MvcAuthEvent $mvcAuthEvent)
    {
        // Add validated identity to ZfcUser storage
        $identity = $mvcAuthEvent->getIdentity();
        if ($identity instanceof AuthenticatedIdentity) {
            /** var AuthenticatedIdentity $identity */
            $user = $this->userService->find($identity->getAuthenticationIdentity()['user_id']);
            if ($user) {
                // It should not be possible to be authenticated without valid user, but in that case
                // we simply don't set the identity to the authentication service. No permissions
                // will then be granted.
                $this->authenticationService->getStorage()->write($user);
            }

        }
    }
 public function testInvokeForBasicAuthHasNoIdentityWhenNotValid()
 {
     $httpAuth = new HttpAuth(array('accept_schemes' => 'basic', 'realm' => 'My Web Site', 'digest_domains' => '/', 'nonce_timeout' => 3600));
     $httpAuth->setBasicResolver(new HttpAuth\ApacheResolver(__DIR__ . '/../TestAsset/htpasswd'));
     $this->listener->setHttpAdapter($httpAuth);
     $this->request->getHeaders()->addHeaderLine('Authorization: Basic xxxxxxxxx');
     $this->listener->__invoke($this->mvcAuthEvent);
     $this->assertNull($this->mvcAuthEvent->getIdentity());
 }
 /**
  * Determine if we have an authentication failure, and, if so, return a 401 response
  *
  * @param MvcAuthEvent $mvcAuthEvent
  * @return null|\Zend\Http\Response
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     if (!$mvcAuthEvent->hasAuthenticationResult()) {
         return;
     }
     $authResult = $mvcAuthEvent->getAuthenticationResult();
     if ($authResult->isValid()) {
         return;
     }
     $mvcEvent = $mvcAuthEvent->getMvcEvent();
     $response = $mvcEvent->getResponse();
     if (!$response instanceof HttpResponse) {
         return $response;
     }
     $response->setStatusCode(401);
     $response->setReasonPhrase('Unauthorized');
     return $response;
 }
 public function testReturnsFalseIfIdentityFailsAcls()
 {
     $listener = $this->listener;
     $this->authorization->addResource('Foo\\Bar\\Controller::index');
     $this->authorization->deny('guest', 'Foo\\Bar\\Controller::index', 'POST');
     $this->mvcAuthEvent->setResource('Foo\\Bar\\Controller::index');
     $this->mvcAuthEvent->getMvcEvent()->getRequest()->setMethod('POST');
     $this->authentication->setIdentity(new GuestIdentity());
     $this->assertFalse($listener($this->mvcAuthEvent));
 }
 /**
  * Determine if we have an authorization failure, and, if so, return a 403 response
  *
  * @param MvcAuthEvent $mvcAuthEvent
  * @return null|\Zend\Http\Response
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     $mvcEvent = $mvcAuthEvent->getMvcEvent();
     $response = $mvcEvent->getResponse();
     if ($mvcAuthEvent->isAuthorized()) {
         if ($response instanceof HttpResponse) {
             if ($response->getStatusCode() != 200) {
                 $response->setStatusCode(200);
             }
         }
         return;
     }
     if (!$response instanceof HttpResponse) {
         return $response;
     }
     $response->setStatusCode(403);
     $response->setReasonPhrase('Forbidden');
     return $response;
 }
    public function testFirstAdapterProvidingTypeIsAuthenticatedAgainst()
    {
        $map = array(
            'Foo\V2' => 'oauth2',
            'Bar\V1' => 'basic',
            'Baz\V3' => 'digest',
        );
        $this->listener->setAuthMap($map);
        $request    = new HttpRequest();
        $routeMatch = new RouteMatch(array('controller' => 'Foo\V2\Rest\Test\TestController'));
        $mvcEvent   = $this->mvcAuthEvent->getMvcEvent();
        $mvcEvent
            ->setRequest($request)
            ->setRouteMatch($routeMatch);

        $types = array('oauth2');
        $adapter1 = $this->getMockBuilder('ZF\MvcAuth\Authentication\AdapterInterface')
            ->disableOriginalConstructor()
            ->getMock();
        $adapter1->expects($this->atLeastOnce())
            ->method('provides')
            ->will($this->returnValue($types));
        $adapter1->expects($this->any())
            ->method('matches')
            ->with($this->equalTo('oauth2'))
            ->will($this->returnValue(true));
        $adapter1->expects($this->any())
            ->method('getTypeFromRequest')
            ->with($this->equalTo($request))
            ->will($this->returnValue('oauth2'));
        $expected = $this->getMockBuilder('ZF\MvcAuth\Identity\AuthenticatedIdentity')
            ->disableOriginalConstructor()
            ->getMock();
        $adapter1->expects($this->once())
            ->method('authenticate')
            ->with($this->equalTo($request), $this->equalTo($this->response))
            ->will($this->returnValue($expected));

        $adapter2 = $this->getMockBuilder('ZF\MvcAuth\Authentication\AdapterInterface')
            ->disableOriginalConstructor()
            ->getMock();
        $adapter2->expects($this->atLeastOnce())
            ->method('provides')
            ->will($this->returnValue($types));
        $adapter2->expects($this->any())
            ->method('getTypeFromRequest')
            ->with($this->equalTo($request))
            ->will($this->returnValue('oauth2'));

        $this->listener->attach($adapter1);
        $this->listener->attach($adapter2);

        $identity = $this->listener->__invoke($this->mvcAuthEvent);
        $this->assertSame($expected, $identity);
    }
 /**
  * Attempt to authorize the discovered identity based on the ACLs present
  *
  * @param MvcAuthEvent $mvcAuthEvent
  * @return bool
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     if ($mvcAuthEvent->isAuthorized()) {
         return;
     }
     $mvcEvent = $mvcAuthEvent->getMvcEvent();
     $request = $mvcEvent->getRequest();
     if (!$request instanceof Request) {
         return;
     }
     $response = $mvcEvent->getResponse();
     if (!$response instanceof Response) {
         return;
     }
     $routeMatch = $mvcEvent->getRouteMatch();
     if (!$routeMatch instanceof RouteMatch) {
         return;
     }
     $identity = $mvcAuthEvent->getIdentity();
     if (!$identity instanceof IdentityInterface) {
         return;
     }
     $resource = $mvcAuthEvent->getResource();
     $identity = $mvcAuthEvent->getIdentity();
     return $this->authorization->isAuthorized($identity, $resource, $request->getMethod());
 }
 /**
  * Listen to authentication events
  *
  * @param MvcAuthEvent $mvcAuthEvent
  * @return mixed
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     $mvcEvent = $mvcAuthEvent->getMvcEvent();
     $request = $mvcEvent->getRequest();
     $response = $mvcEvent->getResponse();
     //Skip authentication for console requests or OPTIONS requests
     if (!$request instanceof HttpRequest || $request->isOptions()) {
         return null;
     }
     //Skip authentication if the requested URI is on the whitelist
     $relPath = $this->_getRelativePath($request);
     foreach ($this->getUriWhitelist() as $pattern) {
         $regex = '/' . str_replace('/', '\\/', $pattern) . '/';
         if (preg_match($regex, $relPath)) {
             return null;
         }
     }
     //Provide our auth adapter with the request and response objects if it needs them
     if (is_callable(array($this->adapter, 'setRequest'))) {
         $this->adapter->setRequest($request);
     }
     if (is_callable(array($this->adapter, 'setResponse'))) {
         $this->adapter->setResponse($response);
     }
     //Ask the adapter to authenticate
     $authService = $mvcAuthEvent->getAuthenticationService();
     $authResult = $authService->authenticate($this->adapter);
     $mvcAuthEvent->setAuthenticationResult($authResult);
     //Create the identity object
     if ($authResult->isValid()) {
         //Create MvcAuth identity
         $resultIdentity = $authResult->getIdentity();
         $identity = new AuthenticatedIdentity($resultIdentity);
         $identity->setName((string) $resultIdentity);
     } else {
         $identity = new GuestIdentity();
     }
     $mvcEvent->setParam('ZF\\MvcAuth\\Identity', $identity);
     return $identity;
 }
 /**
  * If the AUTHORIZATION HTTP header is found, validate and return the user, otherwise default to 'guest'
  * @param \ZF\MvcAuth\MvcAuthEvent $e
  * @return \Application\Authentication\AuthenticatedIdentity|\ZF\MvcAuth\Identity\GuestIdentity
  */
 public function __invoke(\ZF\MvcAuth\MvcAuthEvent $e)
 {
     $guest = new \ZF\MvcAuth\Identity\GuestIdentity();
     $header = $e->getMvcEvent()->getRequest()->getHeader('AUTHORIZATION');
     if (!$header) {
         return $guest;
     }
     $token = $header->getFieldValue();
     $jwt = new \OAuth2\Encryption\Jwt();
     $key = $this->config['cryptoKey'];
     $tokenData = $jwt->decode($token, $key);
     // If the token is invalid, give up
     if (!$tokenData) {
         return $guest;
     }
     $user = $this->entityManager->getRepository(\Application\Model\User::class)->findOneById($tokenData['id']);
     if (!$user) {
         return $guest;
     }
     \Application\Model\User::setCurrentUser($user);
     $identity = new \Application\Authentication\AuthenticatedIdentity($user);
     return $identity;
 }
Example #24
0
 /**
  * Trigger the authorization event
  *
  * @param MvcEvent $mvcEvent
  * @return null|Response
  */
 public function authorization(MvcEvent $mvcEvent)
 {
     if (!$mvcEvent->getRequest() instanceof HttpRequest || $mvcEvent->getRequest()->isOptions()) {
         return;
     }
     $responses = $this->events->trigger(MvcAuthEvent::EVENT_AUTHORIZATION, $this->mvcAuthEvent, function ($r) {
         return is_bool($r) || $r instanceof Response;
     });
     $result = $responses->last();
     if (is_bool($result)) {
         $this->mvcAuthEvent->setIsAuthorized($result);
         return;
     }
     if ($result instanceof Response) {
         return $result;
     }
 }
 public function authorization(MvcAuthEvent $event)
 {
     /** @var \ZF\MvcAuth\Identity\AuthenticatedIdentity $identity */
     $identity = $event->getIdentity();
     if (!$identity instanceof IdentityInterface || $identity instanceof GuestIdentity) {
         return;
     }
     $method = $event->getMvcEvent()->getRequest()->getMethod();
     /** @var \ZF\MvcAuth\Authorization\AclAuthorization $authorization */
     $authorization = $event->getAuthorizationService();
     $sl = $event->getMvcEvent()->getApplication()->getServiceManager();
     /** @var \Zend\Permissions\Acl\Assertion\AssertionInterface $resourceAssertion */
     $resourceAssertion = $sl->get('Zfegg\\Admin\\MvcAuth\\Authorization\\ResourceAssertion');
     if (!$authorization->hasRole($identity)) {
         $authorization->addRole($identity);
     }
     if (!$authorization->hasResource($event->getResource())) {
         $authorization->addResource($event->getResource());
     }
     $authorization->deny($identity, $event->getResource(), $method, $resourceAssertion);
 }
 /**
  * @group 83
  */
 public function testAllowsAdaptersToReturnResponsesAndReturnsThemDirectly()
 {
     $map = ['Foo\\V2' => 'custom'];
     $this->listener->setAuthMap($map);
     $request = new HttpRequest();
     $routeMatch = $this->createRouteMatch(['controller' => 'Foo\\V2\\Rest\\Test\\TestController']);
     $mvcEvent = $this->mvcAuthEvent->getMvcEvent();
     $mvcEvent->setRequest($request)->setRouteMatch($routeMatch);
     $types = ['custom'];
     $adapter = $this->getMockBuilder('ZF\\MvcAuth\\Authentication\\AdapterInterface')->disableOriginalConstructor()->getMock();
     $adapter->expects($this->atLeastOnce())->method('provides')->will($this->returnValue($types));
     $adapter->expects($this->any())->method('getTypeFromRequest')->with($this->equalTo($request))->will($this->returnValue('custom'));
     $adapter->expects($this->any())->method('matches')->with($this->equalTo('custom'))->will($this->returnValue(true));
     $response = new HttpResponse();
     $response->setStatusCode(401);
     $adapter->expects($this->once())->method('authenticate')->with($this->equalTo($request), $this->equalTo($this->response))->will($this->returnValue($response));
     $this->listener->attach($adapter);
     $result = $this->listener->__invoke($this->mvcAuthEvent);
     $this->assertSame($response, $result);
 }
 /**
  * Attempt to authorize the discovered identity based on the ACLs present
  *
  * @param MvcAuthEvent $mvcAuthEvent
  * @void
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     $imageService = $this->getServiceLocator()->get('AqilixAPI\\Image\\Service\\Image');
     $authService = $mvcAuthEvent->getAuthorizationService();
     $config = $this->getServiceLocator()->get('Config')['authorization'];
     $imageService->setUser($this->getServiceLocator()->get('image.authenticated.user'));
     $identity = $mvcAuthEvent->getIdentity();
     if ($identity instanceof \ZF\MvcAuth\Identity\GuestIdentity) {
         return;
     }
     // resource:method
     $requestedResource = $mvcAuthEvent->getResource() . ':' . $mvcAuthEvent->getMvcEvent()->getRequest()->getMethod();
     foreach ($config['scopes'] as $scope => $scopeConfig) {
         $resource = $scopeConfig['resource'] . ':' . $scopeConfig['method'];
         // if authorization resource equals to requested resource
         if ($resource == $requestedResource) {
             // check scope in identity
             if (!in_array($scope, explode(' ', $identity->getAuthenticationIdentity()['scope']))) {
                 return $mvcAuthEvent->getMvcEvent()->getResponse()->setStatusCode(401);
             }
         }
     }
 }
Example #28
0
 public function onAuthenticationPost(MvcAuthEvent $e)
 {
     $this->services->setService('api-identity', $e->getIdentity());
 }
Example #29
0
 /**
  * @depends testAuthorizedFlagIsFalseByDefault
  */
 public function testAuthorizedFlagIsMutable()
 {
     $this->mvcAuthEvent->setIsAuthorized(true);
     $this->assertTrue($this->mvcAuthEvent->isAuthorized());
 }
Example #30
0
    /**
     * Attempt to authenticate the current request.
     *
     * @param Request $request
     * @param Response $response
     * @param MvcAuthEvent $mvcAuthEvent
     * @return false|IdentityInterface False on failure, IdentityInterface
     *     otherwise
     */
    public function authenticate(Request $request, Response $response, MvcAuthEvent $mvcAuthEvent)
    {
        $this->httpAuth->setRequest($request);
        $this->httpAuth->setResponse($response);

        $result = $this->authenticationService->authenticate($this->httpAuth);
        $mvcAuthEvent->setAuthenticationResult($result);

        if (! $result->isValid()) {
            return false;
        }

        $resultIdentity = $result->getIdentity();

        // Pass fully discovered identity to AuthenticatedIdentity instance
        $identity = new Identity\AuthenticatedIdentity($resultIdentity);

        // But determine the name separately
        $name = $resultIdentity;
        if (is_array($resultIdentity)) {
            $name = isset($resultIdentity['username'])
                ? $resultIdentity['username']
                : (string) array_shift($resultIdentity);
        }
        $identity->setName($name);

        return $identity;
    }