laravel GuzzleHttp发布与CSRF

时间:2019-06-11 07:48:06

标签: laravel

我正在尝试使用第二台服务器上的GuzzleHttp将请求发布到第一台服务器 http://imei.sy/imei 有csrf_field() 错误: 500内部错误`响应 那么如何使用csrf_filed发布

我在本地创建同一台服务器

当我在第一台服务器上停止csrf发布成功

  <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use function GuzzleHttp\Promise\each;
use GuzzleHttp\Client as GuzzleClient;

class Guz extends Controller
{
    //
    //public $url = "http://127.0.0.1:8001/add";
    public $url = "http://imei.sy/imei";

    // Make Get request , re
    public function getGuzzleRequest()
        {
            $client = new \GuzzleHttp\Client();
            $request = $client->get($this->url);
            $response = $request->getBody();
        // dd( (string) $response);
        return $this->get_string_between( (string) $response,"token\" content=\"","\">");

        }
public function postGuzzleRequest()
    {

        $client = new \GuzzleHttp\Client();
        $body = [
            'imei' => '99999',
            //'price' => 333,
            '_token'=> $this->getGuzzleRequest()

        ];
        $r = $client->request('POST', $this->url, [

            'form_params' => $body
       ]);

        $response = $r->getBody()->getContents();

        dd($response);


    }

    private function get_string_between($string, $start, $end){ // Get
    if($start != ''){ 
        $string = ' ' . $string;
        $ini = strpos($string, $start);
        if ($ini == 0) return '';
        $ini += strlen($start);
    }
    else{
        $ini = 0;
    }

    if ($end == '') { 
        return substr($string, $ini);
    }
    else{
        $len = strpos($string, $end, $ini) - $ini; 
        return substr($string, $ini, $len);
    }
}
}


Route::get('/guzg',"Guz@getGuzzleRequest");
Route::get('/guzp',"Guz@postGuzzleRequest");

错误: 419个未知状态的响应

2 个答案:

答案 0 :(得分:0)

根据the api reference,您将标头作为参数传递给请求:

 $r = $client->request('POST', 'http://127.0.0.1:8001/add', [
      'headers'     => ['X-CSRF-Token'=> csrf_token()]
      'form_params' => $params
 ]);

答案 1 :(得分:0)

我认为使用csrf令牌不是对第二台服务器进行身份验证的正确方法,也许第二台服务器可以使用oauth2或jwt作为身份验证的API。