Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my Authorization Header giving me a 401 in Guzzle?

Tags:

php

guzzle

I am getting a 401 on Guzzle 4.2 and the same setup works on Postman. Code below.

// Create a client with a base URL
    $client = new GuzzleHttp\Client(['base_url' => 'cloud.feedly.com/v3/streams/contents?streamId=user/user-id/category/global.all&count=1']);

    // Send a request to https://github.com/notifications
    $response = $client->get();

    //Auth
   $response->addHeader('Authorization', "auth-code");


    //send
    $r = $response->send();

   dd($r->json());

The error is:

GuzzleHttp \ Exception \ ClientException (401) 
Client error response [url] cloud.feedly.com/v3/streams/contents?streamId=user/user-id/global.all&count=1 [status code] 401 [reason phrase] Unauthorized
like image 678
Ali Gajani Avatar asked Dec 29 '25 18:12

Ali Gajani


2 Answers

Looking at the documentation page as per this line:

$response = $client->get();

It will send a get request, with no authorisation, hence the 401 response.

Try the following instead

// Create a client with a base URL.
$client = new GuzzleHttp\Client();

$request = $client-> createRequest('GET', 'cloud.feedly.com/v3/streams/contents?streamId=user/user-id/category/global.all&count=1');

$request->setHeader('Authorization', "auth-code");

// Send.
$response = $client->send($request);

dd($response->json());

The above creates a request, set the authorisation header on it. Then once prepared it actually sends it.

I think it worked in Postman because your headers are set, if you remove the authorization header it will likely fail there too.

I have not tested this but think it will work.

like image 95
Shaun Avatar answered Jan 01 '26 06:01

Shaun


$response = $client->get('GET', 'cloud.feedly.com/v3/streams/contents?streamId=user/user-id/category/global.all&count=1', ['auth' =>  ['YOUR_USERNAME', 'YOUR_PASSWORD']]);

The 401 error means you should authenticate yourself with a valid username and password

Regards

like image 24
Andrea Borgogelli Avveduti Avatar answered Jan 01 '26 07:01

Andrea Borgogelli Avveduti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!