/**
  * Receive SendGrid Events
  *
  * @return mixed
  */
 public function eventAction()
 {
     /**
      * If Basic Auth is configured, authenticate the request
      */
     if ($this->auth) {
         $this->auth->setRequest($this->getRequest());
         $this->auth->setResponse($this->getResponse());
         $result = $this->auth->authenticate();
         if (!$result->isValid()) {
             return $this->appError('Authentication Failed', $this->getResponse()->getStatusCode(), 'auth_error');
         }
     }
     /**
      * All SendGrid Requests are POSTed
      */
     if (!$this->getRequest()->isPost()) {
         return $this->appError('Method Not Allowed', 405, 'general_error');
     }
     /**
      * Trigger Events for Listeners
      */
     $this->emitter->receiveRequest($this->getRequest());
     /**
      * Return an Empty 200 Response
      */
     return $this->getResponse();
 }
 /**
  * @param ServiceLocatorInterface $services
  * @throws ServiceNotCreatedException
  * @return false|HttpAuthAdapter
  */
 public function createService(ServiceLocatorInterface $services)
 {
     // If no configuration present, nothing to create
     if (!$services->has('config')) {
         return false;
     }
     $config = $services->get('config');
     // If no HTTP adapter configuration present, nothing to create
     if (!isset($config['zf-mvc-auth']['authentication']['http'])) {
         return false;
     }
     $httpConfig = $config['zf-mvc-auth']['authentication']['http'];
     if (!isset($httpConfig['accept_schemes']) || !is_array($httpConfig['accept_schemes'])) {
         throw new ServiceNotCreatedException('"accept_schemes" is required when configuring an HTTP authentication adapter');
     }
     if (!isset($httpConfig['realm'])) {
         throw new ServiceNotCreatedException('"realm" is required when configuring an HTTP authentication adapter');
     }
     if (in_array('digest', $httpConfig['accept_schemes'])) {
         if (!isset($httpConfig['digest_domains']) || !isset($httpConfig['nonce_timeout'])) {
             throw new ServiceNotCreatedException('Both "digest_domains" and "nonce_timeout" are required when configuring an HTTP digest authentication adapter');
         }
     }
     $httpAdapter = new HttpAuth(array_merge($httpConfig, array('accept_schemes' => implode(' ', $httpConfig['accept_schemes']))));
     if (in_array('basic', $httpConfig['accept_schemes']) && isset($httpConfig['htpasswd'])) {
         $httpAdapter->setBasicResolver(new HttpAuth\ApacheResolver($httpConfig['htpasswd']));
     }
     if (in_array('digest', $httpConfig['accept_schemes']) && isset($httpConfig['htdigest'])) {
         $httpAdapter->setDigestResolver(new HttpAuth\FileResolver($httpConfig['htdigest']));
     }
     return $httpAdapter;
 }
Example #3
0
 public function testAuthenticateReturnsAuthenticatedIdentityIfValidCredentialsProvidedInAuthorizationHeader()
 {
     $httpAuth = new HttpAuth(['accept_schemes' => 'basic', 'realm' => 'My Web Site', 'digest_domains' => '/', 'nonce_timeout' => 3600]);
     $httpAuth->setBasicResolver(new HttpAuth\ApacheResolver(__DIR__ . '/../TestAsset/htpasswd'));
     $adapter = new HttpAdapter($httpAuth, $this->authentication);
     $this->request->getHeaders()->addHeaderLine('Authorization: Basic dXNlcjp1c2Vy');
     $result = $adapter->authenticate($this->request, $this->response, $this->event);
     $this->assertInstanceOf('ZF\\MvcAuth\\Identity\\AuthenticatedIdentity', $result);
 }
 public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
 {
     $config = $container->get('Recurly\\ModuleConfig');
     $authConfig = $config['notification']['security']['authentication']['auth_adapter'];
     $authAdapter = new AuthAdapter($authConfig['config']);
     $basicResolver = new FileResolver();
     $basicResolver->setFile($authConfig['passwd_file']);
     $authAdapter->setBasicResolver($basicResolver);
     return $authAdapter;
 }
 /**
  * {@inheritdoc}
  */
 public function createService(ServiceLocatorInterface $digestServiceLocator)
 {
     if (empty($this->digestConfig)) {
         $this->digestConfig = $digestServiceLocator->get('Config');
     }
     $authDigestConfig = $this->digestConfig['authentication_digest']['adapter'];
     $authDigestAdapter = new HttpAdapter($authDigestConfig['config']);
     $digest = new FileResolver();
     $digest->setFile($authDigestConfig['digest']);
     $authDigestAdapter->setDigestResolver($digest);
     return $authDigestAdapter;
 }
 /**
  * {@inheritdoc}
  */
 public function createService(ServiceLocatorInterface $basicServiceLocator)
 {
     if (empty($this->basicConfig)) {
         $this->basicConfig = $basicServiceLocator->get('Config');
     }
     $authBasicConfig = $this->basicConfig['authentication_basic']['adapter'];
     $authBasicAdapter = new HttpAdapter($authBasicConfig['config']);
     $basic = new FileResolver();
     $basic->setFile($authBasicConfig['basic']);
     $authBasicAdapter->setBasicResolver($basic);
     return $authBasicAdapter;
 }
 private function createBasicAuthAdapter(array $config)
 {
     if (empty($config['username']) || empty($config['password'])) {
         throw new \RuntimeException('Cannot setup Basic HTTP auth without both username and password');
     }
     $realm = isset($config['realm']) ? $config['realm'] : 'Password Required';
     $resolver = new BasicInMemoryResolver($config['username'], $config['password']);
     $options = ['realm' => $realm, 'accept_schemes' => 'basic'];
     $adapter = new BasicHttpAuth($options);
     $adapter->setBasicResolver($resolver);
     return $adapter;
 }
 /**
  * Genrate Authentication Adapter Object
  * @param ServiceLocatorInterface $serviceLocator service manager 
  * @return \Zend\Authentication\Adapter\Http
  */
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     $config = $serviceLocator->get('config');
     $authConfig = $config['book_app']['auth_adapter'];
     $basicResolver = new FileResolver();
     $basicResolver->setFile($authConfig['basic_passwd_file']);
     $digestResolver = new FileResolver();
     $digestResolver->setFile($authConfig['digest_passwd_file']);
     $authAdapter = new HttpAdapter($authConfig['config']);
     $authAdapter->setBasicResolver($basicResolver);
     $authAdapter->setDigestResolver($digestResolver);
     return $authAdapter;
 }
Example #9
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;
    }
Example #10
0
    /**
     * Create an HttpAuth instance based on the configuration passed.
     * 
     * @param array $config 
     * @return HttpAuth
     * @throws ServiceNotCreatedException if any required elements are missing
     */
    public static function factory(array $config)
    {
        if (! isset($config['accept_schemes']) || ! is_array($config['accept_schemes'])) {
            throw new ServiceNotCreatedException(
                '"accept_schemes" is required when configuring an HTTP authentication adapter'
            );
        }

        if (! isset($config['realm'])) {
            throw new ServiceNotCreatedException(
                '"realm" is required when configuring an HTTP authentication adapter'
            );
        }

        if (in_array('digest', $config['accept_schemes'])) {
            if (! isset($config['digest_domains'])
                || ! isset($config['nonce_timeout'])
            ) {
                throw new ServiceNotCreatedException(
                    'Both "digest_domains" and "nonce_timeout" are required '
                    . 'when configuring an HTTP digest authentication adapter'
                );
            }
        }

        $httpAdapter = new HttpAuth(array_merge(
            $config,
            array(
                'accept_schemes' => implode(' ', $config['accept_schemes'])
            )
        ));

        if (in_array('basic', $config['accept_schemes'])
            && isset($config['htpasswd'])
        ) {
            $httpAdapter->setBasicResolver(new ApacheResolver($config['htpasswd']));
        }

        if (in_array('digest', $config['accept_schemes'])
            && isset($config['htdigest'])
        ) {
            $httpAdapter->setDigestResolver(new FileResolver($config['htdigest']));
        }

        return $httpAdapter;
    }
 /**
  * Authenticate
  *
  * @throws Exception\RuntimeException
  * @return Authentication\Result
  */
 public function authenticate()
 {
     if (empty($this->request)) {
         throw new Exception\RuntimeException('Request and Response objects must be set before calling authenticate()');
     }
     if ($this->request->getUri()->getScheme() != 'https') {
         return new Result(Result::FAILURE_UNCATEGORIZED, array(), array('Http authentication must be over https'));
     }
     return parent::authenticate();
 }
Example #12
0
 /**
  * 
  * @param type $authService
  * @param type $em
  * @param \App\MvcEvent $e
  * @return type
  */
 public function tryHttpAuth($authService, $em, MvcEvent $e)
 {
     $resolver = new DoctrineResolver($em, '\\Aaa\\Entity\\User');
     $adapter = new Http(['realm' => 'Max', 'accept_schemes' => 'basic']);
     $adapter->setBasicResolver($resolver);
     $adapter->setRequest($e->getRequest());
     // zato da se ne poĊĦiljajo http auth challenge nastavimo novi response, ki
     // ne vpliva na pravi response
     $adapter->setResponse(new Response());
     // shranim si doctrine adapter
     $originalAdapter = $authService->getAdapter();
     $authService->setAdapter($adapter);
     /* @var $authService AuthenticationService */
     $authResult = $authService->authenticate();
     if ($authResult->isValid()) {
         $identity = $authResult->getIdentity();
         $authService->getStorage()->write($identity);
     } else {
         $authService->setAdapter($originalAdapter);
         $identity = null;
     }
     return $identity;
 }
 public function testInvokeForDigestAuthAddsAuthorizationHeader()
 {
     $httpAuth = new HttpAuth(array('accept_schemes' => 'digest', 'realm' => 'User Area', 'digest_domains' => '/', 'nonce_timeout' => 3600));
     $httpAuth->setDigestResolver(new HttpAuth\FileResolver(__DIR__ . '/../TestAsset/htdigest'));
     $this->listener->setHttpAdapter($httpAuth);
     $this->listener->__invoke($this->mvcAuthEvent);
     $authHeaders = $this->response->getHeaders()->get('WWW-Authenticate');
     $authHeader = $authHeaders[0];
     $this->assertRegexp('#^Digest realm="User Area", domain="/", nonce="[a-f0-9]{32}", opaque="e66aa41ca5bf6992a5479102cc787bc9", algorithm="MD5", qop="auth"$#', $authHeader->getFieldValue());
 }
 public function setupHttpBasicAuth()
 {
     $httpAuth = new HttpAuth(['accept_schemes' => 'basic', 'realm' => 'My Web Site', 'digest_domains' => '/', 'nonce_timeout' => 3600]);
     $httpAuth->setBasicResolver(new HttpAuth\ApacheResolver(__DIR__ . '/../TestAsset/htpasswd'));
     $this->listener->setHttpAdapter($httpAuth);
 }
 /**
  * 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');
     }
 }
Example #16
0
 /**
  * Acts like a client sending the given Authenticate header value.
  *
  * @param  string $clientHeader Authenticate header value
  * @param  string $scheme       Which authentication scheme to use
  * @return array Containing the result, the response headers, and the status
  */
 public function _doAuth($clientHeader, $scheme)
 {
     // Set up stub request and response objects
     $request = $this->getMock('Zend\\Controller\\Request\\Http');
     $response = new HTTPResponse();
     $response->setHttpResponseCode(200);
     $response->headersSentThrowsException = false;
     // Set stub method return values
     $request->expects($this->any())->method('getRequestUri')->will($this->returnValue('/'));
     $request->expects($this->any())->method('getMethod')->will($this->returnValue('GET'));
     $request->expects($this->any())->method('getServer')->will($this->returnValue('PHPUnit'));
     $request->expects($this->any())->method('getHeader')->will($this->returnValue($clientHeader));
     // Select an Authentication scheme
     switch ($scheme) {
         case 'basic':
             $use = $this->_basicConfig;
             break;
         case 'digest':
             $use = $this->_digestConfig;
             break;
         case 'both':
         default:
             $use = $this->_bothConfig;
     }
     // Create the HTTP Auth adapter
     $a = new \Zend\Authentication\Adapter\Http($use);
     $a->setBasicResolver($this->_basicResolver);
     $a->setDigestResolver($this->_digestResolver);
     // Send the authentication request
     $a->setRequest($request);
     $a->setResponse($response);
     $result = $a->authenticate();
     $return = array('result' => $result, 'status' => $response->getHttpResponseCode(), 'headers' => $response->getHeaders());
     return $return;
 }
Example #17
0
 /**
  * Acts like a client sending the given Authenticate header value.
  *
  * @param  string $clientHeader Authenticate header value
  * @param  string $scheme       Which authentication scheme to use
  * @return array Containing the result, the response headers, and the status
  */
 public function _doAuth($clientHeader, $scheme)
 {
     // Set up stub request and response objects
     $response = new Response();
     $response->setStatusCode(200);
     $headers = new Headers();
     $headers->addHeaderLine('Proxy-Authorization', $clientHeader);
     $headers->addHeaderLine('User-Agent', 'PHPUnit');
     $request = new Request();
     $request->setUri('http://localhost/');
     $request->setMethod('GET');
     $request->setHeaders($headers);
     // Select an Authentication scheme
     switch ($scheme) {
         case 'basic':
             $use = $this->_basicConfig;
             break;
         case 'digest':
             $use = $this->_digestConfig;
             break;
         case 'both':
         default:
             $use = $this->_bothConfig;
     }
     // Create the HTTP Auth adapter
     $a = new \Zend\Authentication\Adapter\Http($use);
     $a->setBasicResolver($this->_basicResolver);
     $a->setDigestResolver($this->_digestResolver);
     // Send the authentication request
     $a->setRequest($request);
     $a->setResponse($response);
     $result = $a->authenticate();
     $return = array('result' => $result, 'status' => $response->getStatusCode(), 'headers' => $response->getHeaders());
     return $return;
 }
 protected function getAuthService()
 {
     $config = array('accept_schemes' => 'basic', 'realm' => 'ref-pays-admin');
     //        if (null == $this->authService){
     $httpAuthAdapter = new Http($config);
     $authService = new AuthenticationService();
     $basicResolver = new FileResolver();
     $basicResolver->setFile(dirname(dirname(dirname(dirname(dirname(__DIR__))))) . '\\public\\files\\basicPasswd.txt');
     $httpAuthAdapter->setBasicResolver($basicResolver);
     $httpAuthAdapter->setRequest($this->getRequest());
     $httpAuthAdapter->setResponse($this->getResponse());
     $result = $httpAuthAdapter->authenticate();
     if (!$result->isValid()) {
         die(var_dump($result->getMessages()));
     }
     die('654645');
     $authService->setAdapter($httpAuthAdapter);
     $this->authService = $authService;
     //        }
     return $this->authService;
 }
Example #19
0
 public function testUnsupportedScheme()
 {
     $response = new Response();
     $headers = new Headers();
     $request = new Request();
     $headers->addHeaderLine('Authorization', 'NotSupportedScheme <followed by a space character');
     $request->setHeaders($headers);
     $a = new Adapter\Http($this->_digestConfig);
     $a->setDigestResolver($this->_digestResolver)->setRequest($request)->setResponse($response);
     $result = $a->authenticate();
     $this->assertEquals($result->getCode(), Authentication\Result::FAILURE_UNCATEGORIZED);
 }
Example #20
0
 public function testUnsupportedScheme()
 {
     $response = $this->getMock('Zend\\Controller\\Response\\Http');
     $request = $this->getMock('Zend\\Controller\\Request\\Http');
     $request->expects($this->any())->method('getHeader')->will($this->returnValue('NotSupportedScheme <followed by a space caracter'));
     $a = new Adapter\Http($this->_digestConfig);
     $a->setDigestResolver($this->_digestResolver)->setRequest($request)->setResponse($response);
     $result = $a->authenticate();
     $this->assertEquals($result->getCode(), Authentication\Result::FAILURE_UNCATEGORIZED);
 }