"BAD CSRF" ao executar PUT usando API, curl e PHP

Tenho uma função muito simples que “deveria” funcionar, mas por algum motivo não está. Alguém pode me ajudar a entender o que estamos fazendo de errado?

Continuamos recebendo o erro “BAD CSRF”.

public function changeName()
{
  $url = 'https://www.website.com/{username}.json';
  $data = ['name' => 'James', 'api_key' => DISCOURSE_API, 'api_username' => 'system'];

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:multipart/form-data'));
  curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

  echo $response = curl_exec($ch);

  if (!$response)
  {
      return false;
  }

}

A propósito, já tentei mover o api_key e o api_username para a URL acima como GET, mas não fez diferença.

1 curtida

You need to put the Api-Key and Api-Username values in the request header. There’s a curl example near the end of this topic that could be helpful: Sync SSO user data with the sync_sso route.

5 curtidas

Thanks a lot! That did the trick.

For anyone else with the same problem:

$url = 'https://www.website.com/{username}.json';
$data = ['name'=>'George'];
$api_key = CUSTOM_DISCOURSE_API;

$headers = array("Content-Type: multipart/form-data;","Api-Key: $api_key","Api-Username: system",);


$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

$result = curl_exec( $ch );

if ( curl_errno( $ch ) !== 0 ) {
   // Handle error, call curl_close( $ch ) and return.
}

curl_close( $ch );

$discourse_user = json_decode( $result );
4 curtidas

Just to add to that, if someone needs to update a “user_field” replace the $data with this:

$data = ['user_fields' => ['1' => 'Something']];

The number “1” being the first user_field I created (as they are assigned by number not name).

2 curtidas

Desde quando isso é obrigatório?
Não encontrei nada no changelog. Criei uma ferramenta há 2 ou 3 anos para criar categorias em lote que funcionava perfeitamente e agora estou recebendo esse erro…

Pedimos desculpas por quaisquer problemas causados. Realizamos uma implementação gradual dessa alteração e notificamos as pessoas da melhor forma possível, mas é difícil identificar todos os casos de uso de depreciação.

2 curtidas