Proceeds to filter the current request for any CSRF mismatch. Forms must provide
its unique name and corresponding generated csrf token.

@throws InvalidCsrfException
17353
public function guard()
    {
        if ($this->isHttpMethodFiltered($this->request->getMethod())) {
            $formName = $this->getProvidedFormName();
            $providedToken = $this->getProvidedCsrfToken();
            if (is_null($formName) || is_null($providedToken)) {
                throw new InvalidCsrfException();
            }
            if (!$this->validateToken($formName, $providedToken)) {
                throw new InvalidCsrfException();
            }
        }
    }
45828
protected function renderCsrfTokenField()
    {
        if (strtolower($this->arguments['method']) === 'get') {
            return '';
        }
        if (!$this->securityContext->isInitialized() || !$this->authenticationManager->isAuthenticated()) {
            return '';
        }
        $csrfToken = $this->securityContext->getCsrfProtectionToken();
        return '<input type="hidden" name="__csrfToken" value="' . htmlspecialchars($csrfToken) . '" />' . chr(10);
    }
570596
private static function validation() {
        if (isset(self::$config['validators'])) {
            $validators = self::$config['validators'];
        }
        else {
            $validators = true;
        }

        // action name validation
        if ($validators === true || (!isset($validators['actionName']) || $validators['actionName'] === true)) {
            if (substr(PHPMVC_ACTION, 0, 2) == '__') {
                throw new ActionNameValidationException();
            }
        }

        // request verification token
        $antiForgeryTokenForAction = InternalHelper::getStaticPropertyValue('\\PhpMvc\\ValidateAntiForgeryToken', 'enable');
        if ($antiForgeryTokenForAction === true || (($validators === true || (!isset($validators['antiForgeryToken']) || $validators['antiForgeryToken'] === true)) && $antiForgeryTokenForAction !== false)) {
            $request = self::$config['httpContext']->getRequest();

            if ($request->isPost()) {
                $post = $request->post();
                $expected = $request->cookies('__requestVerificationToken');

                if (!isset($post)) { $post = array(); }

                if (
                    (isset($expected) && $expected !== 'false' && (!isset($post['__requestVerificationToken']) || $post['__requestVerificationToken'] != $expected)) ||
                    (isset($expected) && $expected === 'false' && !empty($post['__requestVerificationToken'])) ||
                    (isset($post['__requestVerificationToken']) && empty($expected))
                   ) {
                    throw new HttpAntiForgeryException();
                }
            }
        }

        // cross site scripting validation
        if ($validators === true || (!isset($validators['crossSiteScripting']) || $validators['crossSiteScripting'] === true)) {
            $request = self::$config['httpContext']->getRequest();

            $get = $request->get();
            $post = $request->post();

            if (!isset($get)) { $get = array(); }
            if (!isset($post)) { $post = array(); }

            $items = array_merge($get, $post);

            foreach ($items as $key => $value) {
                $isDangerousString = CrossSiteScriptingValidation::IsDangerousString($key) || CrossSiteScriptingValidation::IsDangerousString($value);
    
                if ($isDangerousString) {
                    $source = null;

                    if (!empty($get[$key])) {
                        $source = '$_GET';
                    }
                    elseif (!empty($post[$key])) {
                        $source = '$_POST';
                    }
    
                    throw new HttpRequestValidationException($source, $key, $value);
                }
            }
        }
    }
754728
public function csrfCheck()
  {
    // Return immediately if CSRF check is disabled.
    if (!$this->csrfCheck) return;

    $control = $this->hiddenFieldSet->getFormControlByName('ses_csrf_token');

    // If CSRF tokens (from session and from submitted form) don't match: possible CSRF attack.
    $ses_csrf_token1 = Abc::$session->getCsrfToken();
    $ses_csrf_token2 = $control->getSubmittedValue();
    if ($ses_csrf_token1!==$ses_csrf_token2)
    {
      throw new BadRequestException('Possible CSRF attack');
    }
  }
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.'));
        }
    }
518129
public static function getCSRFToken() {
        $allHeaders = array_change_key_case(parent::getHeaders(), CASE_UPPER);

        if (array_key_exists('X-CSRF-TOKEN', $allHeaders)) {
            return $allHeaders['X-CSRF-TOKEN'];
        } else {
            throw new \Exception(ExceptionMessages::CSRF_TOKEN_NOT_FOUND);
        }
    }
792164
function ensureCsrfToken(request) {
    const originalRequest = request;
    const method = request.method.toUpperCase();
    const isCsrfExempt = authenticatedAPIClient.isCsrfExempt(originalRequest.url);
    if (!isCsrfExempt && CSRF_PROTECTED_METHODS.includes(method)) {
      const url = new Url(request.url);
      const { protocol } = url;
      const { host } = url;
      const csrfToken = csrfTokens[host];
      if (csrfToken) {
        request.headers[CSRF_HEADER_NAME] = csrfToken;
      } else {
        if (!queueRequests) {
          queueRequests = true;
          authenticatedAPIClient.getCsrfToken(protocol, host)
            .then((response) => {
              queueRequests = false;
              PubSub.publishSync(CSRF_TOKEN_REFRESH, response.data.csrfToken);
            });
        }

        return new Promise((resolve) => {
          logInfo(`Queuing API request ${originalRequest.url} while CSRF token is retrieved`);
          PubSub.subscribeOnce(CSRF_TOKEN_REFRESH, (msg, token) => {
            logInfo(`Resolving queued API request ${originalRequest.url}`);
            csrfTokens[host] = token;
            originalRequest.headers[CSRF_HEADER_NAME] = token;
            resolve(originalRequest);
          });
        });
      }
    }
    return request;
  }
147176
public static function csrfInput()
    {
        return Html::hiddenInput(\Yii::$app->request->csrfParam, \Yii::$app->request->csrfToken);
    }
775186
protected function filtering()
    {
        $app = Yii::$app;
        if ($this->statusCode) {
            if (is_integer($this->statusCode)) {
                if ($app->getRequest()->getIsAjax()) {
                    $app->getResponse()->setStatusCode(self::STATUS_CODE_OK);
                } else {
                    $app->getResponse()->setStatusCode($this->statusCode);
                    if ($this->retryAfter){
                        $app->getResponse()->getHeaders()->set('Retry-After', $this->retryAfter);
                    }
                }
            } else {
                throw new InvalidConfigException('Parameter "statusCode" should be an integer.');
            }
        }
        // Check users
        if ($this->users) {
            if (is_array($this->users)) {
                $this->disable = $app->getUser()->getIdentity()
                    ? in_array($app->getUser()->getIdentity()->{$this->usernameAttribute}, $this->users)
                    : false;
            } elseif (is_string($this->users)) {
                $this->disable = $app->getUser()->getIdentity()->{$this->usernameAttribute} === $this->users;
            } else {
                throw new InvalidConfigException('Parameter "users" should be an array or string.');
            }
        }
        // Check roles
        if ($this->roles) {
            if (is_array($this->roles)) {
                foreach ($this->roles as $role) {
                    $this->disable = $this->disable || $app->getUser()->can($role);
                }
            } else {
                throw new InvalidConfigException('Parameter "roles" should be an array.');
            }
        }
        // Check URL's
        if ($this->urls) {
            if (is_array($this->urls)) {
                $this->disable = $this->disable || in_array($app->getRequest()->getPathInfo(), $this->urls);
            } else {
                throw new InvalidConfigException('Parameter "urls" should be an array.');
            }
        }
        // Check IP's
        if ($this->ips) {
            if (is_array($this->ips)) {
                foreach ($this->ips as $filter) {
                    $this->disable = $this->disable || $this->checkIp($filter);
                }
            } elseif (is_string($this->ips)){
                $this->disable = $this->disable || $this->checkIp($this->ips);
            } else {
                throw new InvalidConfigException('Parameter "ips" should be an array.');
            }
        }
        if (!$this->disable) {
            if ($this->route === 'maintenance/index') {
                $app->controllerMap['maintenance'] = 'brussens\maintenance\controllers\MaintenanceController';
            }
            $app->catchAll = [$this->route];
        } else {
            $app->getResponse()->setStatusCode(self::STATUS_CODE_OK);
        }
    }
957111
protected function checkCsrf($id = 'lexik-translation', $query = '_token')
    {
        if (!$this->has('security.csrf.token_manager')) {
            return;
        }

        $request = $this->get('request_stack')->getCurrentRequest();

        if (!$this->isCsrfTokenValid($id, $request->get($query))) {
            throw $this->createAccessDeniedException('Invalid CSRF token');
        }
    }
1216569
public static function csrfCheck() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST' || $_SERVER['REQUEST_METHOD'] == 'PUT' || $_SERVER['REQUEST_METHOD'] == 'DELETE') {
            $request = Request::all();

            if (!isset($request['token']) && !Request::getCSRFToken()) {
                throw new RouteException(ExceptionMessages::CSRF_TOKEN_NOT_FOUND);
            }

            if (isset($request['token'])) {
                $token = $request['token'];
            } elseif (Request::getCSRFToken()) {
                $token = Request::getCSRFToken();
            }

            if (!Csrf::checkToken($request['token'])) {
                throw new RouteException(ExceptionMessages::CSRF_TOKEN_NOT_MATCHED);
            }
        }
    }
596890
def form_invalid(self, form, context=None, **kwargs):
        
        if not context:
            context = {}

        context['errors'] = form.errors
        return super(ApiFormView, self).render_to_response(context=context,
                                                           status=400)
997771
public function check() {
        if (! self::$active) {
            return;
        }
        
        // Check sessions are enabled.
        if (session_id() === '') {
            throw new \Exception('Sessions are required to use the CSRF Guard middleware.');
        }
        
        if (isset($_SESSION["csrf_time"])) {
            $expired = (time() - $_SESSION["csrf_time"]) > 3600;
        } else {
            $expired = true;
        }
        
        if (isset($_GET["expire_token"])) {
            $_SESSION["csrf_time"] = time() - 10000;
        }
        
        if (! isset($_SESSION[$this->key]) || $expired) {
            $_SESSION[$this->key] = sha1(serialize($_SERVER) . rand(0, 0xffffffff));
            $_SESSION["csrf_time"] = time();
        }
        
        $token = $_SESSION[$this->key];
        // Validate the CSRF token.
        if (in_array($this->app->request()->getMethod(), array('POST', 'PUT', 'DELETE'))) {
            $userToken = $this->app->request()->post($this->key);
       
            if ($token !== $userToken) {
                $this->app->halt(400, 'Invalid or missing or expired CSRF token.');
            }
        }
        // Assign CSRF token key and value to view.
        self::$token = $token;
    }
200732
public function validateCookie(WebRequest $request)
    {
        if ($request->cookie(self::TOKEN_COOKIE_NAME) != $request->post(self::TOKEN_COOKIE_NAME)) {
            throw new CsrfViolationException();
        }
    }
761856
public function onKernelRequest(GetResponseEvent $event): void
    {
        if (!$event->isMasterRequest()) {
            return;
        }

        $request = $event->getRequest();

        if ($request->attributes->get(SetIsApiRequestListener::API_FLAG_NAME) !== true) {
            return;
        }

        if ($this->csrfTokenValidator->validateCsrfToken($request, $this->csrfTokenId)) {
            return;
        }

        throw new AccessDeniedHttpException('Missing or invalid CSRF token');
    }
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.'));
        }
    }
1272386
def csrf(request):
    
    def _get_val():
        token = get_token(request)
        if token is None:
            # In order to be able to provide debugging info in the
            # case of misconfiguration, we use a sentinel value
            # instead of returning an empty dict.
            return 'NOTPROVIDED'
        else:
            token = force_bytes(token, encoding='latin-1')
            key = force_bytes(
                get_random_string(len(token)),
                encoding='latin-1'
            )
            value = b64_encode(xor(token, key))
            return force_text(b'$'.join((key, value)), encoding='latin-1')
    _get_val = lazy(_get_val, text_type)

    return {'csrf_token': _get_val()}