We expect status code 404 for a successful authentication, otherwise the endpoint will return 401 unauthorized
@return boolean
@throws \Http\Client\Exception
433443
public function checkCredentials()
    {
        try {
            $requestHeader = array_merge_recursive($this->httpHeader, $this->config->getShopHeader());

            $request = $this->messageFactory->createRequest(
                'GET',
                $this->config->getBaseUrl() . '/engine/rest/merchants/',
                $requestHeader
            );
            $request = $this->basicAuth->authenticate($request);
            $responseCode = $this->httpClient->sendRequest($request)->getStatusCode();
        } catch (TransferException $e) {
            $this->getLogger()->debug('Check credentials: Error - ' . $e->getMessage());
            return false;
        }

        if ($responseCode === 404) {
            $this->getLogger()->debug('Check credentials: Valid');
            return true;
        }

        $this->getLogger()->debug('Check credentials: Invalid - Received status code: ' . $responseCode);
        return false;
    }
830579
public function trySubdomainUnauthenticatedGet()
    {
        $this->reset();
        $url = 'http://autodiscover.' . $this->tld . self::AUTODISCOVER_PATH;
        $ch = curl_init();
        $opts = array(
            CURLOPT_URL                 => $url,
            CURLOPT_HTTPGET             => true,
            CURLOPT_RETURNTRANSFER      => true,
            CURLOPT_TIMEOUT             => 4,
            CURLOPT_CONNECTTIMEOUT      => $this->connection_timeout,
            CURLOPT_FOLLOWLOCATION      => false,
            CURLOPT_HEADER              => false,
            CURLOPT_HEADERFUNCTION      => array($this, 'readHeaders'),
            CURLOPT_HTTP200ALIASES      => array(301, 302),
            CURLOPT_IPRESOLVE           => CURL_IPRESOLVE_V4
        );
        curl_setopt_array($ch, $opts);
        $this->last_response    = curl_exec($ch);
        $this->last_info        = curl_getinfo($ch);
        $this->last_curl_errno  = curl_errno($ch);
        $this->last_curl_error  = curl_error($ch);

        if ($this->last_info['http_code'] == 302
            || $this->last_info['http_code'] == 301) {
            if ($this->tryViaUrl($this->last_response_headers['location'])) {
                return self::AUTODISCOVERED_VIA_UNAUTHENTICATED_GET;
            }
        }

        return false;
    }
91001
public function authenticate()
	{
		if (!empty($_REQUEST['openid_mode'])) {
			switch ($_REQUEST['openid_mode']) {
				case 'id_res':
					$this->id_res();
					return true;
					break;

				case 'cancel':
					$this->cancel();
					break;

				default:
					throw new HttpException(400, Yii::t('yii', 'Your request is invalid.'));
					break;
			}
		} else {
			$this->processRequest();
		}

		return false;
	}
856023
public function isSuccess()
    {
        $statuscode = $this->response->getStatusCode();

        if(!in_array($statuscode, [200, 204], true))
        {
            throw new Exception('HTTP Code ' . $statuscode . ' ' . $this->response->getBody());
        }

        return true;
    }
825818
public function authorizationEndpoint() {
		$endpoint = $this->getset('authorization_endpoint', func_get_args());
		return $this->validateEndpoint($endpoint ?: self::URI_AUTHORIZE);
	}
702072
public function execute()
    {
        if (! $this->ch) {
            throw new Exception('Curl request not initiated');
        }

        $statusCode = (int) isset($this->lushOptions['return_status']) ? $this->lushOptions['return_status'] : 200;
        $contentType = isset($this->lushOptions['return_content_type']) ? $this->lushOptions['return_content_type'] : 'text';

        $this->headers['url'] = $this->ch;
        $this->headers['http_code'] = $statusCode;

        $this->executed = true;

        return $this->createResponse($statusCode, $contentType);
    }
158749
protected function _get()
	{
		$this->_lastRequestsResponse = Requests::post(
			$this->_config->getEndpoint(),
			$this->_buildHeader()
		);
		return $this->_lastRequestsResponse->success;
	}
412630
public function authenticate()
    {
        if (!is_null($this->token)) {
            return;
        }

        $response = $this->authenticationResponse();

        if (!$response->hasHeader('X-Auth-Token')) {
            throw new AuthenticationFailedException('Given credentials are wrong.', 403);
        }

        if (!$response->hasHeader('X-Storage-Url')) {
            throw new RuntimeException('Storage URL is missing.', 500);
        }

        $this->token = $response->getHeaderLine('X-Auth-Token');
        $this->storageUrl = $response->getHeaderLine('X-Storage-Url');
    }
780370
public function getIsAuthenticated()
	{
		if (!$this->authenticated) {
			try {
				$proxy = $this->getProxy();
				$this->authenticated = $proxy->hasValidAccessToken();
			} catch (\OAuth\Common\Exception\Exception $e) {
				throw new ErrorException($e->getMessage(), $e->getCode(), 1, $e->getFile(), $e->getLine(), $e);
			}
		}
		return parent::getIsAuthenticated();
	}
804652
protected function retryMiddleware()
    {
        return Middleware::retry(function (
            $retries,
            RequestInterface $request,
            ResponseInterface $response = null
        ) {
            // Limit the number of retries to 2
            if ($retries < $this->app->config->get('http.max_retries', 1) && $response && $body = $response->getBody()) {
                // Retry on server errors
                $response = json_decode($body, true);

                if (!empty($response['errcode']) && in_array(abs($response['errcode']), [40001, 40014, 42001], true)) {
                    $this->accessToken->refresh();
                    $this->app['logger']->debug('Retrying with refreshed access token.');

                    return true;
                }
            }

            return false;
        }, function () {
            return abs($this->app->config->get('http.retry_delay', 500));
        });
    }
213652
public function validateRequest()
    {
        $request = $this->framework->getRequest();
        
        // Parse the authorization information
        $authorization = $this->parseAuthorizationString($request->getHeader('Authorization'));
        $publicKey = $authorization['publicKey'];
        $hmac = $authorization['hmac'];
        
        // Verify the public key
        if (!$this->tokenManager->hasTokenForPublicKey($publicKey)) {
            return false;
        }
        
        // Load the token
        $token = $this->tokenManager->getTokenForPublicKey($publicKey);
        
        // Get the needed data
        $route = $request->getRoute();
        $data = $request->getParams();
        
        $result = $this->restHelper->validateRequest($token->getApiKey(), $hmac, $route, $data);
        
        if ($result) {
            return $token;
        }
        
        return false;
    }
645033
protected function checkAuth()
	{
		try {

			// get the JWT from the headers
			list($jwt) = sscanf($_SERVER["HTTP_AUTHORIZATION"], 'Bearer %s');

			// init the jwt auth class
			$authenticator = new JWTAuthenticator(new User());

			// get the application secret key
			$config     = \Erdiko::getConfig();
			$secretKey  = $config["site"]["secret_key"];

			// collect login params
			$params = array(
				'secret_key'    =>  $secretKey,
				'jwt'           =>  $jwt
			);

			$user = $authenticator->verify($params, 'jwt_auth');

			//TODO check the user's permissions via Resource & Authorization

			// no exceptions? welp, this is a valid request
			return true;
		} catch (\Exception $e) {
			return true;
		}
	}
155129
public function logout()
    {
        if ($this->check()) {
            $this->matrix()->request('POST', $this->endpoint('logout'), [], [
                'access_token' => $this->data['access_token']
            ]);
            $this->setData(null);
            return true;
        }
        throw new \Exception('Not authenticated');
    }
1138903
protected function handleError()
    {
        $okStatus = array(
            100, 200, 201,
        );
        $messages = array(
            401 => 'Authorization required',
            403 => 'Forbidden request',
            404 => 'Not found',
            406 => 'Not accepted',
            422 => 'Unprocessable entity',
            500 => 'Internal server error',
            501 => 'Method not implemented',
        );

        if (isset($messages[$this->httpStatus])) {
            throw new HttpStatusException($messages[$this->httpStatus], $this->httpStatus);
        }
        if (!in_array($this->httpStatus, $okStatus)) {
            throw new UnknownHttpStatusException('Unknown http status: ' . $this->httpStatus);
        }
    }
533637
public function endpoint() {
		$endpoint = $this->getset('endpoint', func_get_args());
		return $this->validateEndpoint($endpoint ?: self::URI_API);
	}
577847
public function doShow()
    {
        if ( ($this->exception instanceof ezcMvcRouteNotFoundException) || ($this->exception instanceof ezpContentNotFoundException ) )
        {
            // we want to return a 404 to the user
            $result = new ezcMvcResult;
            $result->status = new ezpRestHttpResponse( ezpHttpResponseCodes::NOT_FOUND, "Not Found" );
            return $result;
        }

        else if ( $this->exception instanceof ezpOauthBadRequestException )
        {
            $result = new ezcMvcResult;
            $result->status = new ezpRestOauthErrorStatus( $this->exception->errorType, $this->exception->getMessage() );
            $result->variables['message'] = $this->exception->getMessage();
            return $result;
        }
        else if ( $this->exception instanceof ezpOauthRequiredException )
        {
            $result = new ezcMvcResult;
            $result->status = new ezpOauthRequired( "eZ Publish REST", $this->exception->errorType, $this->exception->getMessage() );
            $result->variables['message'] = $this->exception->getMessage();
            return $result;
        }
        else if ( $this->exception instanceof ezpContentAccessDeniedException )
        {
            $result = new ezcMvcResult;
            $result->variables['message'] = $this->exception->getMessage();
            $result->status = new ezpRestHttpResponse( ezpHttpResponseCodes::FORBIDDEN, $this->exception->getMessage() );
            return $result;
        }
        else if ( $this->exception instanceof ezpRouteMethodNotAllowedException )
        {
            $result = new ezpRestMvcResult;
            $result->status = new ezpRestStatusResponse(
                ezpHttpResponseCodes::METHOD_NOT_ALLOWED,
                $this->exception->getMessage(),
                array( 'Allow' => implode( ', ', $this->exception->getAllowedMethods() ) )
            );
            return $result;
        }

        $result = new ezcMvcResult;
        $result->variables['message'] = $this->exception->getMessage();
        $result->status = new ezpRestHttpResponse( ezpHttpResponseCodes::SERVER_ERROR, $this->exception->getMessage() );
        return $result;
    }
483317
public function requestCredentialsToken()
    {
        $payload = base64_encode($this->getClientId() . ':' . $this->getClientSecret());

        $parameters = [
            'grant_type' => 'client_credentials',
        ];

        $headers = [
            'Authorization' => 'Basic ' . $payload,
        ];

        $response = $this->request->account('POST', '/api/token', $parameters, $headers);
        $response = $response['body'];

        if (isset($response->access_token)) {
            $this->accessToken = $response->access_token;
            $this->expirationTime = time() + $response->expires_in;
            $this->scope = isset($response->scope) ? $response->scope : $this->scope;

            return true;
        }

        return false;
    }