Ejemplo n.º 1
0
 public function __construct($bypassPaths = array(), $bypassAuth = false)
 {
     $this->useOAuth2 = API_USE_OAUTH;
     if ($this->useOAuth2) {
         $this->initOAth2();
         // Don't check for authorization when requesting a token or docs
         $temp = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
         $lastPath = str_replace($_SERVER['QUERY_STRING'], '', $temp[count($temp) - 1]);
         $lastPath = str_replace('?', '', $lastPath);
         if ($bypassAuth == false && $lastPath != 'authorize' && $lastPath != 'docs') {
             $continue = true;
             foreach ($bypassPaths as $path) {
                 if ($lastPath == $path) {
                     $continue = false;
                 }
             }
             if ($continue) {
                 // Check for a valid token
                 if (!$this->oauthServer->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {
                     // Not authorized!
                     $this->oauthServer->getResponse()->send();
                     die;
                 }
             }
         }
     }
 }
 /**
  * Execute this middleware.
  *
  * @param  ServerRequestInterface $request  The PSR7 request.
  * @param  ResponseInterface      $response The PSR7 response.
  * @param  callable               $next     The Next middleware.
  *
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $oauth2Request = RequestBridge::toOAuth2($request);
     foreach ($this->scopes as $scope) {
         if ($this->server->verifyResourceRequest($oauth2Request, null, $scope)) {
             $this->container['token'] = $this->server->getResourceController()->getToken();
             return $next($request, $response);
         }
     }
     return ResponseBridge::fromOAuth2($this->server->getResponse());
 }
 /**
  * Helper method to verify a resource request, allowing return early on success cases
  *
  * @param array $scopes Scopes required for authorization
  *
  * @return boolean True if the request is verified, otherwise false
  */
 private function verify(array $scopes = [null])
 {
     foreach ($scopes as $scope) {
         if (is_array($scope)) {
             $scope = implode(' ', $scope);
         }
         if ($this->server->verifyResourceRequest(MessageBridge::newOauth2Request($this->app->request()), null, $scope)) {
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 4
0
 /**
  * {@inheritDoc}
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     try {
         $oauth2request = Util::convertRequestFromPsr7($request);
         if (!$this->server->verifyResourceRequest($oauth2request)) {
             return Util::convertResponseToPsr7($this->server->getResponse(), $response);
         }
         $request = $request->withAttribute('access_token', $this->server->getAccessTokenData($oauth2request));
     } catch (\Exception $ex) {
         return new JsonResponse(['error' => $ex->getMessage(), 'error_description' => $ex->getMessage()], 500);
     }
     return $next($request, $response);
 }
Ejemplo n.º 5
0
 /**
  * @param Route $route
  * @throws \Slim\Exception\Stop
  */
 private function checkAuth(Route $route)
 {
     $request = OAuth2\Request::createFromGlobals();
     $scopeRequired = [];
     if ($route->isSecure()) {
         $scopeRequired = 'admin';
     }
     if (!$this->oauth->verifyResourceRequest($request, NULL, $scopeRequired)) {
         $response = $this->oauth->getResponse();
         $this->app->response()->status($response->getStatusCode());
         $response->send();
         $this->app->stop();
     }
 }
 /**
  * Test resource (/oauth/resource)
  */
 public function resourceAction()
 {
     // Handle a request for an OAuth2.0 Access Token and send the response to the client
     if (!$this->server->verifyResourceRequest($this->getOAuth2Request())) {
         $response = $this->server->getResponse();
         $parameters = $response->getParameters();
         $errorUri = isset($parameters['error_uri']) ? $parameters['error_uri'] : null;
         return new ApiProblemResponse(new ApiProblem($response->getStatusCode(), $parameters['error_description'], $errorUri, $parameters['error']));
     }
     $httpResponse = $this->getResponse();
     $httpResponse->setStatusCode(200);
     $httpResponse->getHeaders()->addHeaders(array('Content-type' => 'application/json'));
     $httpResponse->setContent(json_encode(array('success' => true, 'message' => 'You accessed my APIs!')));
     return $httpResponse;
 }
 protected function authorize()
 {
     $authorized = false;
     if ($this->server->verifyResourceRequest(OAuth2Request::createFromGlobals())) {
         // authorized
         $authorized = true;
     } else {
         $request = $this->getRequest();
         $token = $request->getPost('token', false);
         if ($token) {
             $authorized = $this->isGoogleAuthorized($token);
         }
     }
     return $authorized ? true : false;
 }
 public function verifyResourceRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $scope = null)
 {
     if ($request === null) {
         $request = $this->module->getRequest();
     }
     return parent::verifyResourceRequest($request, $response, $scope);
 }
Ejemplo n.º 9
0
 /**
  * {@inheritDoc}
  */
 public function authenticate(TokenInterface $token)
 {
     $oauthRequest = OAuthRequest::createFromRequest($token->request);
     // Not authenticated
     if (!$this->server->verifyResourceRequest($oauthRequest)) {
         throw new AuthenticationException('OAuth2 authentication failed');
     }
     $userData = $this->server->getAccessTokenData($oauthRequest);
     $user = $this->userProvider->findById($userData['user_id']);
     $roles = $this->roleFinder->findRoleNamesByUserId($user->getId());
     $user->setRoles($roles);
     $authenticatedToken = new OAuth2UserToken($roles);
     $authenticatedToken->setUser($user);
     $authenticatedToken->setAuthenticated(true);
     $authenticatedToken->setOAuthToken($token->getOAuthToken());
     return $authenticatedToken;
 }
 /**
  * Validates a request and takes a scope value that could result
  * in a user id being put into the request if it's valid.
  *
  * @param HttpFoundation\Request $request
  * @param string $scope
  * @return null|HttpFoundation\Response
  */
 public function validateRequest(HttpFoundation\Request $request, $scope)
 {
     $this->log->addDebug(print_r($request, true), ['namespace' => 'HackTheDinos\\Controllers\\OAuth', 'method' => 'validateRequest', 'type' => 'request', 'scope' => $scope]);
     $bridgeRequest = HttpFoundationBridge\Request::createFromRequest($request);
     if ($this->server->verifyResourceRequest($bridgeRequest, null, $scope)) {
         //Put the userId into the request if we're validating at the user scope
         if ($scope === 'user') {
             $token = $this->server->getAccessTokenData($bridgeRequest);
             $request->request->set('userId', $token['user_id']);
         } else {
             //Set the userId to 0 which should make any
             //searches relying on this being valid to fail.
             $request->request->set('userId', 0);
         }
         return null;
     }
     $this->log->addWarning('Failed to validate request', ['namespace' => 'HackTheDinos\\Controllers\\OAuth', 'method' => 'validateRequest', 'scope' => $scope]);
     return new HttpFoundation\Response('Not Authorized', 401);
 }
 public function testAccessResourceWithJwtAccessTokenUsingSecondaryStorage()
 {
     // add the test parameters in memory
     $server = $this->getTestServer();
     $request = TestRequest::createPost(array('grant_type' => 'client_credentials', 'client_id' => 'Test Client ID', 'client_secret' => 'TestSecret'));
     $server->handleTokenRequest($request, $response = new Response());
     $this->assertNotNull($JwtAccessToken = $response->getParameter('access_token'));
     // make a call to the resource server using the crypto token
     $request = TestRequest::createPost(array('access_token' => $JwtAccessToken));
     // create a resource server with the "memory" storage from the grant server
     $resourceServer = new Server($server->getStorage('client_credentials'));
     $this->assertTrue($resourceServer->verifyResourceRequest($request));
 }
Ejemplo n.º 12
0
 public function resource($path)
 {
     // Handle a request for an OAuth2.0 Access Token and send the response to the client
     if (!$this->server->verifyResourceRequest(Request::createFromGlobals())) {
         $this->server->getResponse()->send();
         die;
     }
     $token = $this->server->getAccessTokenData(Request::createFromGlobals());
     $return = array();
     if (is_callable($this->resourceHandler)) {
         $return = call_user_func($this->resourceHandler, $path, $token['user_id']);
     }
     echo json_encode($return);
 }
Ejemplo n.º 13
0
 /**
  * Validates a request and takes a scope value that could result
  * in a user id being put into the request if it's valid. The
  * passThrough flag will allow the request to continue when it
  * would otherwise fail with a 401 response.
  *
  * @param HttpFoundation\Request $request
  * @param string $scope
  * @param bool $passThrough
  * @return null|HttpFoundation\Response
  */
 public function validateRequest(HttpFoundation\Request $request, $scope, $passThrough = false)
 {
     $this->log->addDebug(print_r($request, true), ['namespace' => 'Alerts\\Controllers\\OAuth2', 'method' => 'validateRequest', 'type' => 'request', 'scope' => $scope]);
     $bridgeRequest = HttpFoundationBridge\Request::createFromRequest($request);
     if ($this->server->verifyResourceRequest($bridgeRequest, null, $scope)) {
         //Put the user into the request if we're validating at the user scope
         if ($scope === 'user') {
             $token = $this->server->getAccessTokenData($bridgeRequest);
             $request->request->set('user', $this->usersRepo->getById($token['user_id']));
         } else {
             //Set the user to null which should make any
             //searches relying on this being valid to fail.
             $request->request->set('user', null);
         }
         return null;
         //If the request shouldn't hard fail. This should only have a few specific use cases.
     } elseif ($passThrough) {
         $this->log->addInfo('OAuth Pass Through', ['namespace' => 'Alerts\\Controllers\\OAuth2', 'method' => 'validateRequest', 'type' => 'request', 'scope' => $scope, 'passThrough' => true]);
         return null;
     }
     $this->log->addInfo('Failed to validate request', ['namespace' => 'Alerts\\Controllers\\OAuth2', 'method' => 'validateRequest', 'scope' => $scope]);
     return new HttpFoundation\Response('Not Authorized', 401);
 }
Ejemplo n.º 14
0
 /**
  * Method executed when the dispatch event is triggered
  *
  * @param MvcEvent $e 
  * @return void
  */
 public static function onDispatch(MvcEvent $e)
 {
     if ($e->getRequest() instanceof \Zend\Console\Request) {
         return;
     }
     if ($e->getRouteMatch()->getMatchedRouteName() == 'login' || $e->getRouteMatch()->getMatchedRouteName() == 'users') {
         return;
     }
     $sm = $e->getApplication()->getServiceManager();
     $usersTable = $sm->get('Users\\Model\\UsersTable');
     $storage = new Pdo($usersTable->adapter->getDriver()->getConnection()->getConnectionParameters());
     $server = new Server($storage);
     if (!$server->verifyResourceRequest(Request::createFromGlobals())) {
         $model = new JsonModel(array('errorCode' => $server->getResponse()->getStatusCode(), 'errorMsg' => $server->getResponse()->getStatusText()));
         $response = $e->getResponse();
         $response->setContent($model->serialize());
         $response->getHeaders()->addHeaderLine('Content-Type', 'application/json');
         $response->setStatusCode($server->getResponse()->getStatusCode());
         return $response;
     }
 }
Ejemplo n.º 15
0
 /**
  * Attempt to authenticate the current request.
  *
  * @param Request $request
  * @param Response $response
  * @param MvcAuthEvent $mvcAuthEvent
  * @return false|Identity\IdentityInterface False on failure, IdentityInterface
  *     otherwise
  */
 public function authenticate(Request $request, Response $response, MvcAuthEvent $mvcAuthEvent)
 {
     $oauth2request = new OAuth2Request($request->getQuery()->toArray(), $request->getPost()->toArray(), [], $request->getCookie() ? $request->getCookie()->getArrayCopy() : [], $request->getFiles() ? $request->getFiles()->toArray() : [], method_exists($request, 'getServer') ? $request->getServer()->toArray() : $_SERVER, $request->getContent(), $request->getHeaders()->toArray());
     // Failure to validate
     if (!$this->oauth2Server->verifyResourceRequest($oauth2request)) {
         $oauth2Response = $this->oauth2Server->getResponse();
         $status = $oauth2Response->getStatusCode();
         // 401 or 403 mean invalid credentials or unauthorized scopes; report those.
         if (in_array($status, [401, 403], true) && null !== $oauth2Response->getParameter('error')) {
             return $this->mergeOAuth2Response($status, $response, $oauth2Response);
         }
         // Merge in any headers; typically sets a WWW-Authenticate header.
         $this->mergeOAuth2ResponseHeaders($response, $oauth2Response->getHttpHeaders());
         // Otherwise, no credentials were present at all, so we just return a guest identity.
         return new Identity\GuestIdentity();
     }
     $token = $this->oauth2Server->getAccessTokenData($oauth2request);
     $identity = new Identity\AuthenticatedIdentity($token);
     $identity->setName($token['user_id']);
     return $identity;
 }
Ejemplo n.º 16
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)
    {
        $content       = $request->getContent();
        $oauth2request = new OAuth2Request(
            $_GET,
            $_POST,
            array(),
            $_COOKIE,
            $_FILES,
            $_SERVER,
            $content,
            $request->getHeaders()->toArray()
        );

        if (! $this->oauth2Server->verifyResourceRequest($oauth2request)) {
            return false;
        }

        $token    = $this->oauth2Server->getAccessTokenData($oauth2request);
        $identity = new Identity\AuthenticatedIdentity($token);
        $identity->setName($token['user_id']);
        return $identity;
    }
Ejemplo n.º 17
0
 /**
  * Access verification method.
  *
  * API access will be denied when this method returns false
  *
  * @return boolean true when api access is allowed; false otherwise
  */
 public function __isAllowed()
 {
     return self::$server->verifyResourceRequest(static::$request);
 }
 /**
  * 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');
     }
 }
Ejemplo n.º 19
0
 public function verifyResourceRequest(HttpRequest $httpRequest)
 {
     $oauthRequest = $this->buildRequest($httpRequest);
     $this->server->verifyResourceRequest($oauthRequest, null);
     return $this->buildResponse($this->determineFormat($httpRequest), new HttpResponse(), $this->server->getResponse());
 }