Create a anti-CSRF token in the session
335949
async def createcsrf(self, csrfarg = '_csrf'):
        
        await self.sessionstart()
        if not csrfarg in self.session.vars:
            self.session.vars[csrfarg] = uuid.uuid4().hex
998442
def csrf_token():
    
    if "_csrf_token" not in session:
        session["_csrf_token"] = os.urandom(128)
    return hmac.new(app.secret_key, session["_csrf_token"],
            digestmod=sha1).hexdigest()
157041
function(req,res,next){
  var token = req.get('X-OOSE-Token')
  if(!token || user.session.token !== token){
    res.status(401)
    res.json({error: 'Invalid session'})
  } else {
    req.session = user.session
    next()
  }
}
365184
def masked_authenticity_token(session, form_options: {}) # :doc:
        action, method = form_options.values_at(:action, :method)

        raw_token = if per_form_csrf_tokens && action && method
          action_path = normalize_action_path(action)
          per_form_csrf_token(session, action_path, method)
        else
          real_csrf_token(session)
        end

        one_time_pad = SecureRandom.random_bytes(AUTHENTICITY_TOKEN_LENGTH)
        encrypted_csrf_token = xor_byte_strings(one_time_pad, raw_token)
        masked_token = one_time_pad + encrypted_csrf_token
        Base64.strict_encode64(masked_token)
      end
721471
def token_new():
    """"""
    form = TokenForm(request.form)
    form.scopes.choices = current_oauth2server.scope_choices()

    if form.validate_on_submit():
        t = Token.create_personal(
            form.data['name'], current_user.get_id(), scopes=form.scopes.data
        )
        db.session.commit()
        session['show_personal_access_token'] = True
        return redirect(url_for(".token_view", token_id=t.id))

    if len(current_oauth2server.scope_choices()) == 0:
        del(form.scopes)

    return render_template(
        "invenio_oauth2server/settings/token_new.html",
        form=form,
    )
565452
public function createCsrfField()
    {
        $fieldName = Config::get('security.csrf.field_name');

        $input = new Input($this->form->expression('input'), [
            'name' => $fieldName,
            'value' => $this->createToken(),
            'type' => 'hidden'
        ]);

        return $input->execute();
    }
970508
function makeSession(session) {
  return {
    authenticated: !!session.token,
    token: session.token,
    scope: session.scope,
    error: session.error,
    errorDescription: session.errorDescription
  };
}
1193827
public static function getStoredToken(): Token
    {
        if (static::$token !== null) {
            return static::$token;
        }

        $sessionKeyName = static::getSessionKeyName();

        if ($sessionKeyName === null || strlen($sessionKeyName) == 0) {
            throw new Exception('Can not get stored CSRF token when session key is not set');
        }

        $token = Session::get($sessionKeyName);

        if ($token === null) {
            throw new SecurityException('There is no stored token on backend');
        }

        static::$token = $token;
        return $token;
    }
366454
public function validateCsrf()
    {
        $tokenService = $this->getServiceLocator()->get(TokenService::SERVICE_ID);

        $tokenName = $tokenService->getTokenName();
        $token = $this->getRequestParameter($tokenName);

        if ( $tokenService->checkToken($token) ) {
            $tokenService->revokeToken($token);
            $newToken = $tokenService->createToken();
            $this->setCookie($tokenName, $newToken, null, '/');
            return true;
        }

        \common_Logger::w('Csrf validation failed');
        throw new \common_exception_Unauthorized();
    }
837275
public function setTokenIntoSession()
    {
        $token = $this->getRandomToken();

        if (empty($this->storage->csrf_tokens)) {
            $this->storage->csrf_tokens = [];
        }

        $this->storage->csrf_tokens = [trim($token) => true];

        $this->token = $token;
    }
839683
public static function _init()
	{
		static::$csrf_token_key = \Config::get('security.csrf_token_key', 'fuel_csrf_token');
		static::$csrf_old_token = \Input::cookie(static::$csrf_token_key, false);

		// if csrf automatic checking is enabled, and it fails validation, bail out!
		if (\Config::get('security.csrf_autoload', true))
		{
			$check_token_methods = \Config::get('security.csrf_autoload_methods', array('post', 'put', 'delete'));
			if (in_array(strtolower(\Input::method()), $check_token_methods) and ! static::check_token())
			{
				throw new \SecurityException('CSRF validation failed, Possible hacking attempt detected!');
			}
		}

		// throw an exception if the output filter setting is missing from the app config
		if (\Config::get('security.output_filter', null) === null)
		{
			throw new \FuelException('There is no security.output_filter defined in your application config file');
		}

		// deal with duplicate filters, no need to slow the framework down
		foreach (array('output_filter', 'uri_filter', 'input_filter') as $setting)
		{
			$config = \Config::get('security.'.$setting, array());
			is_array($config) and \Config::set('security.'.$setting, \Arr::unique($config));
		}
	}
36843
def _get_csrf_token(self):
        """"""
        from bs4 import BeautifulSoup
        home_response = self.session.get(self.URLS['login'])
        self._log('Home', home_response)
        assert home_response.status_code == 200, \
            'Could not load Easyname login page.'

        html = BeautifulSoup(home_response.content, 'html.parser')
        self._log('Home', html)
        csrf_token_field = html.find('input', {'id': 'loginxtoken'})
        assert csrf_token_field is not None, 'Could not find login token.'
        return csrf_token_field['value']
846329
private function getCsrfToken()
    {
        if(!isset($this->vitex->req->session['_csrf_token'])){
            $token = md5(rand(0,999).time());
            $this->vitex->req->session['_csrf_token'] = $token;
        } else {
            $token = $this->vitex->req->session['_csrf_token'];
        }
        $this->saveScrefToken($token);
        $this->vitex->applyHook("sys.after.generate_csrf_token",$token);
        return $token;
    }
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');
    }
  }
388429
protected function controlCsrf()
    {
        if ($this->isPosted()
            && !$this->isInternalRoute()
            && (!isset($this->current_route['token']) || !empty($this->current_route['token']))) {

            $token = $this->request->post('token', '', false, 'string');

            if (!gplcart_string_equals($token, $this->token)) {
                $this->response->outputError403();
            }
        }
    }
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")
1060873
def get_csrf_token(response):
    
    cookie_headers = [
        h.decode('ascii') for h in response.headers.getlist("Set-Cookie")
    ]
    if not cookie_headers:
        return None
    csrf_headers = [
        h for h in cookie_headers if h.startswith("csrftoken=")
    ]
    if not csrf_headers:
        return None
    match = re.match("csrftoken=([^ ;]+);", csrf_headers[-1])
    return match.group(1)