【问题标题】:PHP Laravel api sent json post with curlPHP Laravel api 发送带有 curl 的 json 帖子
【发布时间】:2020-08-31 00:00:02
【问题描述】:

我的问题如下

我有一个计数器 api,它使用 laravel。我需要将一个帖子作为 json 发送到这个 api,但是当我发送没有标题时,419 页面返回过期,当我发送标题时,我得到一个 @ 987654322@ 错误。但是,我从元数据中获取 csrf 标记并将其放入标题中。

我要指出的是我没有使用 Laravel,我要发布的 api 是使用 Laravel。

我的代码:

<?php 
$data = 'JSON DATA'; 
$wow = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_URL,"laravel api url");

$dom = new DOMDocument;
$dom->loadHTML($resultado);
$tags = $dom->getElementsByTagName('meta');
for ($i = 0; $i < $tags->length; $i++) {
    $grab = $tags->item($i);
    if ($grab->getAttribute('name') == 'csrf-token') {
        $token = $grab->getAttribute('content');
    }
}

ob_start();      // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output

curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_URL,"LARAVEL API URL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $wow);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json, text/plain, */*',
    'Accept-Encoding: gzip, deflate, br',
    'X-CSRF-TOKEN: '.$token.''));

$buf2 = curl_exec ($ch);

curl_close ($ch);

echo htmlentities($buf2);
?>  

【问题讨论】:

  • 为什么不直接排除特定路由甚至不需要 CSRF?
  • @Ron 因为这次我收到 419 page expired 错误。
  • 419 正是由于 CSRF ..
  • @Ron 我猜是这样,因为当我通过标题删除 csrf 行时,我得到 419。
  • 您可以在 Laravel 中声明,甚至不会检查特定路由的 CSRF .. 一旦这样做,就不会出现 419 错误...因为没有令牌过期..跨度>

标签: php laravel


【解决方案1】:

如果这对您的应用有意义,您可以为特定的 route 完全禁用 CSRF token

检查the DOCs并编辑app/Http/Middleware/VerifyCsrfToken.php

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

【讨论】:

    猜你喜欢
    • 2022-08-07
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    相关资源
    最近更新 更多