/** * @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(); }
/** * 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()); }
/** * 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; }
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)); }
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 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); }
public function testInvokeForBasicAuthSetsGuestIdentityWhenValid() { $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'); $identity = $this->listener->__invoke($this->mvcAuthEvent); $this->assertInstanceOf('ZF\\MvcAuth\\Identity\\GuestIdentity', $identity); $this->assertEquals('guest', $identity->getRoleId()); return array('identity' => $identity, 'mvc_event' => $this->mvcAuthEvent->getMvcEvent()); }
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); }
/** * 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); } } } }
/** * 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; }
/** * 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; }
/** * 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; }
/** * @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); }
/** * 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; }
/** * Listen to the authentication event * * @param MvcAuthEvent $mvcAuthEvent * @return mixed */ public function __invoke(MvcAuthEvent $mvcAuthEvent) { $mvcEvent = $mvcAuthEvent->getMvcEvent(); $request = $mvcEvent->getRequest(); $response = $mvcEvent->getResponse(); if (!$request instanceof HttpRequest || $request->isOptions()) { return; } $type = false; if ($this->httpAdapter instanceof HttpAuth) { $this->httpAdapter->setRequest($request); $this->httpAdapter->setResponse($response); } $authHeader = $request->getHeader('Authorization'); if ($authHeader) { $headerContent = trim($authHeader->getFieldValue()); // we only support headers in the format: Authorization: xxx yyyyy if (strpos($headerContent, ' ') === false) { $identity = new Identity\GuestIdentity(); $mvcEvent->setParam('ZF\\MvcAuth\\Identity', $identity); return $identity; } list($type, $credential) = preg_split('# #', $headerContent, 2); } if (!$type && !in_array($request->getMethod(), $this->requestsWithoutBodies) && $request->getHeaders()->has('Content-Type') && $request->getHeaders()->get('Content-Type')->match('application/x-www-form-urlencoded') && $request->getPost('access_token')) { $type = 'oauth2'; } if (!$type && null !== $request->getQuery('access_token')) { $type = 'oauth2'; } if (!$type) { if ($this->httpAdapter instanceof HttpAuth) { $this->httpAdapter->challengeClient(); } $identity = new Identity\GuestIdentity(); $mvcEvent->setParam('ZF\\MvcAuth\\Identity', $identity); return $identity; } switch (strtolower($type)) { case 'basic': case 'digest': if (!$this->httpAdapter instanceof HttpAuth) { $identity = new Identity\GuestIdentity(); $mvcEvent->setParam('ZF\\MvcAuth\\Identity', $identity); return $identity; } $auth = $mvcAuthEvent->getAuthenticationService(); $result = $auth->authenticate($this->httpAdapter); $mvcAuthEvent->setAuthenticationResult($result); if ($result->isValid()) { $resultIdentity = $result->getIdentity(); // Pass full discovered identity to AuthenticatedIdentity object $identity = new Identity\AuthenticatedIdentity($resultIdentity); // But determine name separately $name = $resultIdentity; if (is_array($resultIdentity)) { $name = isset($resultIdentity['username']) ? $resultIdentity['username'] : (string) $resultIdentity; } $identity->setName($name); // Set in MvcEvent $mvcEvent->setParam('ZF\\MvcAuth\\Identity', $identity); return $identity; } $identity = new Identity\GuestIdentity(); $mvcEvent->setParam('ZF\\MvcAuth\\Identity', $identity); return $identity; case 'oauth2': case 'bearer': if (!$this->oauth2Server instanceof OAuth2Server) { $identity = new Identity\GuestIdentity(); $mvcEvent->setParam('ZF\\MvcAuth\\Identity', $identity); return $identity; } $content = $request->getContent(); $oauth2request = new OAuth2Request($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER, $content); if ($this->oauth2Server->verifyResourceRequest($oauth2request)) { $token = $this->oauth2Server->getAccessTokenData($oauth2request); $identity = new Identity\AuthenticatedIdentity($token); $identity->setName($token['user_id']); $mvcEvent->setParam('ZF\\MvcAuth\\Identity', $identity); return $identity; } $identity = new Identity\GuestIdentity(); $mvcEvent->setParam('ZF\\MvcAuth\\Identity', $identity); return $identity; case 'token': throw new \Exception('zf-mvc-auth has not yet implemented a "token" authentication adapter'); } }
public function testGetMvcEvent() { $this->assertInstanceOf('Zend\\Mvc\\MvcEvent', $this->mvcAuthEvent->getMvcEvent()); }
/** * @param \ZF\MvcAuth\MvcAuthEvent $mvcAuthEvent * @param \Zend\Mvc\MvcEvent $mvcEvent * @param \Zend\Http\Request $request * @param \Zend\Http\Request $response * @param \Phpro\MvcAuthToken\TokenServer $tokenServer * @param \Phpro\MvcAuthToken\Adapter\AdapterInterface $adapter */ public function it_should_return_guest_identity_when_invalid($mvcAuthEvent, $mvcEvent, $request, $response, $tokenServer, $adapter) { $mvcAuthEvent->getMvcEvent()->willReturn($mvcEvent); $mvcEvent->getRequest()->willReturn($request); $mvcEvent->getResponse()->willReturn($response); $this->mockTokenServer($tokenServer); $this->setTokenServer($tokenServer); $this->setAdapter($adapter); // Invalid token authentication $tokenServer->authenticate()->willReturn(false); $this->__invoke($mvcAuthEvent)->shouldReturnAnInstanceOf('ZF\\MvcAuth\\Identity\\GuestIdentity'); // Exception while reading token data $tokenServer->authenticate()->willThrow('Phpro\\MvcAuthToken\\Exception\\TokenException'); $this->__invoke($mvcAuthEvent)->shouldReturnAnInstanceOf('ZF\\MvcAuth\\Identity\\GuestIdentity'); }