Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
Muchas solicitudes AJAX a la vez con protección CSRF

Hola a todos.

Mi aplicación web se basa en solicitudes asíncronas. El widget del temporizador está funcionando y actualizando su estado cada segundo por AJAX (sí, es necesario).

Estoy enviando con cada AJAX mis tokens CSRF:

 project_data.append(csrf_name_key,csrf_name_value); project_data.append(csrf_value_key,csrf_value_value);

Y en respuesta estoy actualizando esas variables globales:

 function setCSRF(response) { csrf_name_key = response.nameKey; csrf_name_value = response.name; csrf_value_key = response.valueKey; csrf_value_value = response.value; }

Todo está bien en general. Pero si voy a hacer otro AJAX, por ejemplo, cuando cambio la tarea en la lista de tareas pendientes a "hecho", a veces termina con un error porque estoy enviando AJAX antes de obtener nuevos tokens de la solicitud anterior.

Realmente no sé cómo hacer para resolver ese problema. La primera idea fue que haría "como una matriz de pila" con 5 tokens diferentes pero una solicitud https = un par de tokens y no puedo generarla.

Tal vez algún tipo de cola de solicitudes ajax, pero hacerlas en el momento adecuado, no lo sé.

Mi pseudo-solución real es "si falla, intente nuevamente un máximo de 10 veces":

 if(e.target.response=="Failed CSRF check!") { if(failedAjax<10) checkForSurvey(); failedAjax++; return; }

En general, funciona, pero aparecen errores en una consola y es una solución muy sucia.

Estoy usando microframework Slim 3 con extensión CSRF. Realmente por favor ayuda con ese problema interesante.

le estare muy agradecido,

Arturo

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Hay algunas opciones para ti:

  1. Use una pila de tokens csrf dentro de su código javascript

  2. Use un token csrf que se puede usar más de una vez (no tan seguro)

  3. Usar una cola para la solicitud

Una pila para las fichas

Slim-Csrf -middleware le brinda funcionalidad, para generar estos tokens, solo necesita llevarlos al lado del cliente. Podría hacer una api para obtener 5 tokens csrf, esta api también consumiría en csrf-token.

Agregue una API y genere los tokens allí.

 $app->get('/foo', function ($request, $response, $args) { // check valid csrf token $tokens = []; for ($i = 0; $i < 5; $i++) { $tokens[] = $this->csrf->generateToken(); } return $response->withJson($tokens); });

Ahora, el token csrf es válido durante toda la sesión del usuario.

Guard::generateToken() devuelve algo como esto:

 array (size=2) 'csrf_name' => string 'csrf58e669ff70da0' (length=17) 'csrf_value' => string '52ac7689d3c6ea5d01889d711018f058' (length=32)

Un token csrf de usos múltiples

Para eso, Slim-Csrf ya proporciona funcionalidad con el modo de persistencia de token. Eso se puede habilitar mediante el constructor o el método Guard::setPersistentTokenMode(bool) . En mi ejemplo, estoy haciendo esto con el método:

 $container['csrf'] = function ($c) { $guard = new \Slim\Csrf\Guard; $guard->setPersistentTokenMode(true); return $guard; };

Aquí el PhpDoc del atributo persistanceTokenMode

 /** * Determines whether or not we should persist the token throughout the duration of the user's session. * * For security, Slim-Csrf will *always* reset the token if there is a validation error. * @var bool True to use the same token throughout the session (unless there is a validation error), * false to get a new token with each request. */

Una cola para las solicitudes ajax.

Agregue una cola para la solicitud, eso podría retrasar la ejecución de su solicitud, pero siempre habrá un token csrf válido.

Esto debería verse como un pseudocódigo ya que aún no lo he probado.

 var requestQueue = []; var isInRequest = false; var csrfKey = ''; // should be set on page load, to have a valid token at the start var csrfValue = ''; function newRequest(onSuccessCallback, data) { // add all parameters you need // add request to the queue requestQueue.push(function() { isInRequest = true; // add to csrf stuff to data $.ajax({ data: xxx url: "serverscript.xxx", success: function(data) { // update csrfKey & csrfValue isInRequest = false; tryExecuteNextRequest(); // try execute next request onSuccessCallback(data); // proceed received data } }}); ); tryExecuteNextRequest(); } function tryExecuteNextRequest() { if(!isInRequest && requestQueue.length != 0) { // currently no request running & var nextRequest = requestQueue.shift(); nextRequest(); // execute next request } }
about 4 years ago · Santiago Trujillo Report

0

En general, simplemente puede eliminar CSRF al no aceptar cookies para la autenticación.

Puede guardar el token de autenticación en localStorage y enviarlo como un encabezado con cada solicitud.

De esta manera, nunca tendrá que preocuparse por CSRF y sus tokens.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!