Check if the Cross-Site-Request-Forgery (CSRF) security token was valid or not.

@return boolean
5262
public function isCsrfValid()
    {
        // csrf protection is disabled.
        if (!$this->isCsrfProtectionEnabled()) {
            return true;
        }

        // the form is not submitted
        if (!$this->isSubmitted()) {
            return true;
        }

        // the form is valid, so the csrf is also valid.
        if ($this->isValid()) {
            return true;
        }

        // the form is invalid. Let's check if the CSRF value is the problem.
        foreach ($this->fields as $field) {
            if ($field instanceof AbstractFormField && $field->getName() == 'csrftoken' && !$field->isValid()) {
                return false;
            }
        }

        // the field is not the problem...
        return true;
    }
497894
protected function verifyCsrfToken($token=null)
    {
        if ($this->options['csrfTokenEnabled']) {
            $token || $token = $this->request->getParam($this->options['csrfTokenName']);
            
            $data = static::getCsrfTokenData();
            
            $res = FormToken::instance()->verify($token, $data);
            
            if ($res['errcode']) {
                $this->stop()->errorInfo = $res;
            }
        }
        
        return $this->errorInfo;
    }
649171
public function isSecurityUser()
    {
        if ($this->securityUser) {
            return true;
        }
        
        /** @var PreAuthenticatedToken $token */
        if (($token = $this->tokenStorage->getToken())
            && ($user = $token->getUser()) instanceof UserInterface ) {
            $this->securityUser = $user;
            return true;
        }
        return false;
    }
752889
public function isValidRequest(): bool
    {
        // If we're running from CLI, requests are always valid, unless we're running the tests.
        if ((!self::inTest() && 'cli' === PHP_SAPI) || false === $this->params->getBotParam('validate_request')) {
            return true;
        }

        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR'] as $key) {
            if (filter_var($_SERVER[$key] ?? null, FILTER_VALIDATE_IP)) {
                $ip = $_SERVER[$key];
                break;
            }
        }

        return Ip::match($ip, array_merge(
            [self::TELEGRAM_IP_RANGE],
            (array) $this->params->getBotParam('valid_ips', [])
        ));
    }
996661
public function valid()
        {
            // Return true if and only if all parts of the URI have passed validation
            return $this->validateUsername()
               && $this->validatePassword()
               && $this->validateHost()
               && $this->validatePort()
               && $this->validatePath()
               && $this->validateQuery()
               && $this->validateFragment();
        }
747066
protected function validateAction()
    {
        $token = (isset($this->validationToken)) ? $this->validationToken : get_class($this);
        if (!$this->app->make('token')->validate($token)) {
            $this->error->add($this->app->make('token')->getErrorMessage());

            return false;
        }
        if (!$this->canAccess()) {
            return false;
        }

        return true;
    }
1344194
protected function checkCsrfToken(Request $request)
    {
        if (!$request->headers->has(self::CSRF_TOKEN_HEADER)) {
            return false;
        }

        return $this->csrfTokenManager->isTokenValid(
            new CsrfToken(
                $this->csrfTokenIntention,
                $request->headers->get(self::CSRF_TOKEN_HEADER)
            )
        );
    }
1227968
def ValidateCSRFTokenOrRaise(request):
  """"""

  # CSRF check doesn't make sense for GET/HEAD methods, because they can
  # (and are) used when downloading files through <a href> links - and
  # there's no way to set X-CSRFToken header in this case.
  if request.method in ("GET", "HEAD"):
    return

  # In the ideal world only JavaScript can be used to add a custom header, and
  # only within its origin. By default, browsers don't allow JavaScript to
  # make cross origin requests.
  #
  # Unfortunately, in the real world due to bugs in browsers plugins, it can't
  # be guaranteed that a page won't set an HTTP request with a custom header
  # set. That's why we also check the contents of a header via an HMAC check
  # with a server-stored secret.
  #
  # See for more details:
  # https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
  # (Protecting REST Services: Use of Custom Request Headers).
  csrf_token = request.headers.get("X-CSRFToken", "").encode("ascii")
  if not csrf_token:
    logging.info("Did not find headers CSRF token for: %s", request.path)
    raise werkzeug_exceptions.Forbidden("CSRF token is missing")

  try:
    decoded = base64.urlsafe_b64decode(csrf_token + b"==")
    digest, token_time = decoded.rsplit(CSRF_DELIMITER, 1)
    token_time = int(token_time)
  except (TypeError, ValueError):
    logging.info("Malformed CSRF token for: %s", request.path)
    raise werkzeug_exceptions.Forbidden("Malformed CSRF token")

  if len(digest) != hashlib.sha256().digest_size:
    logging.info("Invalid digest size for: %s", request.path)
    raise werkzeug_exceptions.Forbidden("Malformed CSRF token digest")

  expected = GenerateCSRFToken(request.user, token_time)
  if not constant_time.bytes_eq(csrf_token, expected):
    logging.info("Non-matching CSRF token for: %s", request.path)
    raise werkzeug_exceptions.Forbidden("Non-matching CSRF token")

  current_time = rdfvalue.RDFDatetime.Now().AsMicrosecondsSinceEpoch()
  if current_time - token_time > CSRF_TOKEN_DURATION.microseconds:
    logging.info("Expired CSRF token for: %s", request.path)
    raise werkzeug_exceptions.Forbidden("Expired CSRF token")
76379
public function isAuthenticated(): bool
    {
        if (!$this->securityContext->canBeInitialized()) {
            return false;
        }

        return array_reduce($this->securityContext->getAuthenticationTokens(), function (bool $isAuthenticated, TokenInterface $token) {
            return $isAuthenticated || $token->isAuthenticated();
        }, false);
    }
1337103
protected function isTokenValid() {
    if ($this->isTokenValid) {
      // already validated
      return true;
    }
    $request = ObjectFactory::getInstance('request');
    $token = $request->hasHeader(self::TOKEN_HEADER) ? $request->getHeader(self::TOKEN_HEADER) :
        $request->getValue(self::TOKEN_HEADER, null);
    $this->isTokenValid = $token != null && $token == $_COOKIE[$this->tokenName];
    return $this->isTokenValid;
  }
770196
public boolean isValidToken() {
        try {
//            Response response = wsBase.path(TEST_CONFIGS).request(MediaType.APPLICATION_JSON_TYPE).get();
//            return response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL;

            LoadZone zone = getLoadZone(LoadZone.AMAZON_US_ASHBURN.uid);
            return zone == LoadZone.AMAZON_US_ASHBURN;
        } catch (Exception e) {
            log.info("API token validation failed: " + e);
        }
        return false;
    }
524946
@Override
    public boolean isValidRequest(Context context) {
        // Check if we are executing an unsafe method
        if (!isUnsafe(context)) {
            return true;
        }

        if (checkCsrfBypass(context)) {
            LOGGER.debug("Bypassing CSRF check for {} {}", context.route().getHttpMethod(), context.route().getUrl());
            return true;
        } else {
            String tokenFromRequest = extractTokenFromRequest(context);
            if (tokenFromRequest == null) {
                LOGGER.error("CSRF Check failed because there is no token in the incoming request headers");
                return false;
            }
            String tokenFromContent = extractTokenFromContent(context);
            if (tokenFromContent == null) {
                LOGGER.error("CSRF Check failed because we are unable to find a token in the incoming request query " +
                        "string or body");
                return false;
            }

            if (compareTokens(tokenFromRequest, tokenFromContent)) {
                return true;
            } else {
                LOGGER.error("CSRF Check failed because the given token is invalid");
                return false;
            }
        }
    }
1347288
public function isValid($token)
    {
        $this->validatePrepared();

        return $this->sessionBag->has(self::CSRF_TKN_NAME) && 
               $this->sessionBag->has(self::CSRF_TKN_TIME) && 
               $this->sessionBag->get(self::CSRF_TKN_NAME) === $token;
    }
918512
public function csrf()
	{
		if ( ! $this->csrf)
		{
			$this->csrf = \Dependency::resolve('security.csrf', array($this->config, \Application::getInstance()->getSession()));
		}

		return $this->csrf;
	}
1195963
public function isValid() {
		$this->apiTokens = $this->_loadApiTokens ();
		$key = $this->_getHeaderToken ();
		if ($this->apiTokens->isExpired ( $key )) {
			return false;
		} else {
			$this->_addHeaderToken ( $key );
			return true;
		}
	}
1179535
function csrf() {
		return Cache::instance()->
			exists(($this->sid?:session_id()).'.@',$data)?
				$data['csrf']:FALSE;
	}
754834
private function hasToken()
    {
        $token = $this->_scopeConfig->getValue('payment/pagseguro/token');
        // check for a e-mail
        if (!isset($token))
            return false;

        // check is the e-mail is valid
        if ($this->isValidToken($token))
            return true;
        return false;
    }