How do I do HTTP basic authentication using Guzzle?

Solution 1:

If you're using Guzzle 5.0 or newer, the docs say that basic auth is specified using the auth parameter:

$client = new GuzzleHttp\Client();
$response = $client->get('http://www.server.com/endpoint', [
    'auth' => [
        'username', 
        'password'
    ]
]);

Please note that the syntax is different if you're using Guzzle 3.0 or earlier. The constructor is different, and you also need to explicitly use the send method on a request to get a response:

$client = new Guzzle\Http\Client();
$request = $client->get('http://www.server.com/endpoint');
$request->setAuth('username', 'password');
$response = $request->send();

Solution 2:

In additional to @amenadiel answer. Sometimes handy specify auth parameters in constructor:

$client = new Client([
    'auth' => ['username', 'password'],
]); 

Then every request will use this default auth parameters.

Solution 3:

This dint work when I used Guzzlev6 and used the advice from @amenadiel. When you use curl, your syntax would look something like

curl -u [email protected]:password http://service.com

behind the scenes it actually takes the "[email protected]:password" bit, base64 encodes it and sends the request with an "Authorization" Header with the encoded value. For this example, that will be:

Authorization: Basic c29tZW9uZUBnbWFpbC5jb206cGFzc3dvcmQ=

Advice from @amenadiel appended an "auth: username,password" header and hence, my authentication kept failing. To achieve this successfully, just craft the header when you are instantiating a Guzzle Client request, i.e

$client = new GuzzleHttp\Client();
$credentials = base64_encode('[email protected]:password');
$response = $client->get('http://www.server.com/endpoint', [
    'Authorization' => ['Basic '.$credentials]
]);

That would append the header as curl would, and whatever service you are trying to connect to will stop yelling at you,

Cheers.

Solution 4:

According to the Guzzle 6 documentation, you can do a request with basic authorization as simple as this:

$client = new Client();

$response = $client->request(
    'POST', /*instead of POST, you can use GET, PUT, DELETE, etc*/
    $url,
    [
      'auth' => ['username', 'password'] /*if you don't need to use a password, just leave it null*/
    ] 
);

echo $response->getBody();

NOTE: You don't need to use base64_encode() at all because it already does it before the request.

I've tested and it works :)

See more at: Guzzle 6 Documentation