Validate the API token

@param  string                 $token    Authentication token
@param  HTTPRequest            $request  HTTP API request
@return true|RESTfulAPIError            True if token is valid OR RESTfulAPIError with details
334693
private function validateAPIToken($token, $request)
    {
        //get owner with that token
        $SQL_token = Convert::raw2sql($token);
        $tokenColumn = $this->tokenConfig['DBColumn'];

        $tokenOwner = DataObject::get_one(
            $this->tokenConfig['owner'],
            "\"" . $this->tokenConfig['DBColumn'] . "\"='" . $SQL_token . "'",
            false
        );

        if ($tokenOwner) {
            //check token expiry
            $tokenExpire = $tokenOwner->{$this->tokenConfig['expireDBColumn']};
            $now = time();
            $life = $this->tokenConfig['life'];

            if ($tokenExpire > ($now - $life)) {
                // check if token should automatically be updated
                if ($this->tokenConfig['autoRefresh']) {
                    $tokenOwner->setField($this->tokenConfig['expireDBColumn'], $now + $life);
                    $tokenOwner->write();
                }
                //all good, log Member in
                if (is_a($tokenOwner, Member::class)) {
                    # this is a login without the logging
                    Config::nest();
                    Config::modify()->set(Member::class, 'session_regenerate_id', true);
                    $identityStore = Injector::inst()->get(IdentityStore::class);
                    $identityStore->logIn($tokenOwner, false, $request);
                    Config::unnest();
                }

                return true;
            } else {
                //too old
                return new RESTfulAPIError(403,
                    'Token expired.',
                    array(
                        'message' => 'Token expired.',
                        'code' => self::AUTH_CODE_TOKEN_EXPIRED,
                    )
                );
            }
        } else {
            //token not found
            //not sure it's wise to say it doesn't exist. Let's be shady here
            return new RESTfulAPIError(403,
                'Token invalid.',
                array(
                    'message' => 'Token invalid.',
                    'code' => self::AUTH_CODE_TOKEN_INVALID,
                )
            );
        }
    }
873595
public static function validate_sig($token, $key)
    {
        try {
            \Firebase\JWT\JWT::decode($token, $key, array('HS256', 'HS384', 'HS512', 'RS256'));
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
1355155
public function verifyChallenge(string $token) : VerifyChallengeResponse
    {
        $request = new VerifyChallenge($token);
        return $this->service->execute($request, $this->position);
    }
367763
private function validateToken($token)
    {
        // Without a session file, no token will validate.
        if (!file_exists($this->config->getSessionFileName()))
        {
            return false;
        }

        $encrypted = file_get_contents($this->config->getSessionFileName()); // Read encrypted session file.

        $plain = Encryption::decrypt($encrypted, $this->config->getSecretKey()); // Decrypt data.
        $file = Spyc::YAMLLoadString($plain); // Parse YAML.

        return $token == $file['token'] && time() < $file['expires']; // Token must be valid and not expired.
    }
88666
private function validateRequest(ServerRequestInterface $request, array &$tokens)
    {
        $data = $request->getParsedBody();

        if (!isset($data[$this->formIndex]) || !isset($data[$this->formToken])) {
            return false;
        }

        $index = $data[$this->formIndex];
        $token = $data[$this->formToken];

        if (!isset($tokens[$index])) {
            return false;
        }

        $stored = $tokens[$index];
        unset($tokens[$index]);

        $lockTo = $request->getUri()->getPath();

        if (!Utils\Helpers::hashEquals($lockTo, $stored['lockTo'])) {
            return false;
        }

        $expected = self::encode(hash_hmac('sha256', ClientIp::getIp($request), base64_decode($stored['token']), true));

        return Utils\Helpers::hashEquals($token, $expected);
    }
1164381
public function authenticate($request) {
		if(!$this->configured)
			return;
		
		$this->checkValidity();
		
		if($this->via == self::HTTP_HEADER)
			$request->addHeader($this->description->http_header, $this->token);
	}
1132185
protected function getTokenFromRequest(Request $request)
    {
        $token = $request->input($this->token) ?: $request->header($this->csrfHeader);

        if (! $token && $header = $request->header($this->xsrfHeader)) {
            $token = $this->encrypter->decrypt($header, static::serialized());
        }

        return $token;
    }
587816
public function validateAuthorization(ServerRequestInterface $request)
    {
        $user = $this->app->make(User::class);

        // Allow logged in users to bypass API authentication entirely if the route allows it
        // This functionality is NOT READY. We will not allow this yet.
        /*
        $route = $request->getAttribute('_route');

        if ($user->checkLogin()) {
            // Return the request with additional attributes
            return $request
                ->withAttribute('oauth_access_token_id', null)
                ->withAttribute('oauth_client_id', null)
                ->withAttribute('oauth_user_id', null)
                ->withAttribute('oauth_scopes', 'session');

            return $request;
        }
        */

        // Delegate the rest to the passed in validator
        return $this->validator->validateAuthorization($request);
    }
374039
protected function _validateToken(ServerRequest $request)
    {
        $cookie = $request->getCookie($this->_config['cookieName']);
        $post = $request->getData($this->_config['field']);
        $header = $request->getHeaderLine('X-CSRF-Token');

        if (!$cookie) {
            throw new InvalidCsrfTokenException(__d('cake', 'Missing CSRF token cookie'));
        }

        if (!Security::constantEquals($post, $cookie) && !Security::constantEquals($header, $cookie)) {
            throw new InvalidCsrfTokenException(__d('cake', 'CSRF token mismatch.'));
        }
    }
439693
public function validateToken($token)
    {
        if (is_string($token)) {
            $token = $this->decodeToken($token);
        }

        if (!isset($token->sdef) || !is_array($token->sdef) || count($token->sdef) !== 3) {
            throw new BadRequestHttpException('sdef should be a sub-definition identifier.');
        }
        list ($sbas_id, $record_id, $subdef) = $token->sdef;

        return array($sbas_id, $record_id, $subdef);
    }
824241
public function tokenIsValid(Request $request, ISession $session) : bool
    {
        if (!$session->has(self::TOKEN_INPUT_NAME)) {
            $session->set(self::TOKEN_INPUT_NAME, \bin2hex(\random_bytes(16)));
        }

        if ($this->tokenShouldNotBeChecked($request)) {
            return true;
        }

        // Try an input
        $token = $request->getInput(self::TOKEN_INPUT_NAME);

        // Try the X-CSRF header
        if ($token === null) {
            $token = $request->getHeaders()->get('X-CSRF-TOKEN');
        }

        // Try the X-XSRF header
        if ($token === null) {
            $token = $request->getHeaders()->get('X-XSRF-TOKEN');
        }

        if ($token === null) {
            return false;
        }

        return \hash_equals($session->get(self::TOKEN_INPUT_NAME), $token);
    }
347519
protected function verifyToken(string $token): bool
    {
        if ($this->token_validation_url) {
            $this->logger->debug('validate oauth2 token via rfc7662 token validation endpoint ['.$this->token_validation_url.']', [
               'category' => get_class($this),
            ]);

            $url = str_replace('{token}', $token, $this->token_validation_url);
        } else {
            $discovery = $this->getDiscoveryDocument();
            if (!(isset($discovery['userinfo_endpoint']))) {
                throw new OidcException\UserEndpointNotSet('userinfo_endpoint could not be determained');
            }

            $this->logger->debug('validate token via openid-connect userinfo_endpoint ['.$discovery['userinfo_endpoint'].']', [
               'category' => get_class($this),
            ]);

            $url = $discovery['userinfo_endpoint'].'?access_token='.$token;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $response = json_decode($result, true);

        if (200 === $code) {
            $attributes = json_decode($result, true);
            $this->logger->debug('successfully verified oauth2 access token via authorization server', [
               'category' => get_class($this),
            ]);

            if (!isset($attributes[$this->identity_attribute])) {
                throw new Exception\IdentityAttributeNotFound('identity attribute '.$this->identity_attribute.' not found in oauth2 response');
            }

            $this->identifier = $attributes[$this->identity_attribute];

            if ($this->token_validation_url) {
                $this->attributes = $attributes;
            } else {
                $this->access_token = $token;
            }

            return true;
        }
        $this->logger->error('failed verify oauth2 access token via authorization server, received status ['.$code.']', [
               'category' => get_class($this),
            ]);

        throw new OidcException\InvalidAccessToken('failed verify oauth2 access token via authorization server');
    }
371772
protected function _validateToken(ServerRequest $request)
    {
        $cookies = $request->getCookieParams();
        $cookie = Hash::get($cookies, $this->_config['cookieName']);
        $post = Hash::get($request->getParsedBody(), $this->_config['field']);
        $header = $request->getHeaderLine('X-CSRF-Token');

        if (!$cookie) {
            throw new InvalidCsrfTokenException(__d('cake', 'Missing CSRF token cookie'));
        }

        if (!Security::constantEquals($post, $cookie) && !Security::constantEquals($header, $cookie)) {
            throw new InvalidCsrfTokenException(__d('cake', 'CSRF token mismatch.'));
        }
    }
1241692
protected function authenticate($request) : bool
  {
    $bearer = substr($request->header('Authorization'), 6);
    $token  = explode(' ', $bearer)[1];

    try {
      $payLoad = $this->validateToken($token);
    }
    catch (TokenValidatorException $e) {
      $this->fails($e);
      cancel();
    }

    $userid   = $payLoad['iss'];
    $provider = $payLoad['pro'];

    $model = config('auth.provider.' . $provider . '.model');

    Auth::grant($model::where('id', $userid)->firstOrFail());

    return true;
  }
318843
private function checkSignature($request)
	{
		if($clientInfo = $this->getClientInfo($request['appId'])){
			if($this->getSign($clientInfo['token'],$request['nonce'],$request['timestamp']) == $request['signature'])
				return true;
			return false;
		}else{
			return false;
		}
	}
235199
public function token(Request $request)
    {
        $user = $this->getUser($request);
        
        $client = $user->clients->first();
        if (null !== $client && $client instanceof Client) {

            $serverRequest = $this->createRequest(
                $client,
                $user->id,
                $request, $scope = []
            );
            $reponse = parent::issueToken($serverRequest);
            $responseArray = json_decode($reponse->content(), true);
            unset($responseArray['refresh_token']);
            return response()->json($responseArray)
                ->setStatusCode($reponse->getStatusCode());
        }
        return response(['error' => 'Please create a client first'], 401);
    }
845974
public function supportRequestToken(Request $request)
    {
        $client = $request->getUser() && $request->getPassword();
        $token = 'refresh_token' == $request->get('grant_type') && $request->get('refresh_token');

        return $client && $token;
    }