David Maloof
David Maloof

Reputation: 23

Laravel guzzle request working on tinker but unauthorized in controller

i'm having a problem that could not get my head around, I have a class that connects to a restful api using Guzzle, it works in tinker, but in the controller I always get a 401 unauthorized error using the same connection data.

ApiConnectionClass

use App\ApiData;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7;
class ApiConnectionClass
{
    var $conn_data;
    var $client;

public function __construct()
{
    $this->conn_data = ApiData::findOrFail(1);
    $this->client = new Client(['base_uri' => $this->conn_data->url]);
}

 public function lista_pruebas(){
    try{
        $response = $this->client->request('GET', 'pruebas/detalles', [
            'verify' => false,
            'headers' => ['Authorization' => 'Bearer ' . $this->conn_data->access_token],
        ]);
    } catch (GuzzleException $e) {
        dump(Psr7\str($e->getRequest()));
        if ($e->hasResponse()) {
            dd(Psr7\str($e->getResponse()));
        }
    }
     return json_decode($response->getBody()->getContents());
 }

in tinker I get the correct json response

$api = new App\Classes\ApiConnectionClass();
$api->lista_pruebas();

ApiController

use App\Classes\ApiConnectionClass;


class ApiController extends Controller
{
    public function lista_pruebas(){
        $api = new ApiConnectionClass();
        $lista = $api->lista_pruebas();

        return view('pruebas.index', compact('lista'));
    }
}

ApiConnectionClass response called from controller

""" HTTP/1.0 401 Unauthorized\r\n Date: Wed, 22 Aug 2018 16:20:58 GMT\r\n Server: Apache/2.4.33 (Win64) PHP/7.2.4\r\n Vary: Authorization\r\n X-Powered-By: PHP/7.2.4\r\n Cache-Control: no-cache, private\r\n Content-Length: 13\r\n Connection: close\r\n Content-Type: text/html; charset=UTF-8\r\n \r\n Unauthorized. """

Upvotes: 1

Views: 735

Answers (1)

eaglebeagle2
eaglebeagle2

Reputation: 98

This doesn't seem like it is an error with what your doing in code because I can see this usage of guzzle everywhere on the web. I do have a couple suggestions however. Tinker uses a different runtime than your application (php-cli vs php-fpm respectively) this could be causing an issue because in one scenario (php-cli) php goes directly from your box to the api server and in the other it goes through your webserver before making the request (php-fpm). The first thing to do would be to clear your laravel cache and config with php artisan cache:clear and php artisan config:clear if that fails I would look into the cross domain restrictions or settings on your web server. Good luck!

Upvotes: 1

Related Questions