How do I do HTTP basic authentication using Guzzle?

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();

A brief addendum

In response to @Matthwew-Knill, yes, you can set a default authorization and implicitly have Guzzle send it in each further request. @Nick’s answer is on point. The client constructor takes every parameter you could think of and then some.

Another approach, if you want to get creative, would be to instantiate the client passing it default headers to send on every further request. Simple auth is, after all, an Authorization header. It’s computed as:

$client = new Client([
  'headers'=>[
       'Authorization'=> Basic base64_encode(<username>:<password>)
   ]
 ]);

Last but not least please note that filling a simple auth dialog happens only once (upon the virst visit of a given session). This is usually achieved by setting a cookie on the visitor’s browser. That cookie in turn contains enough info for the server to identify its matching active session.

Usually, Guzzle requests are stateless, but you can configure Guzzle with a middleware chain to either modify request or responses, for debug purposes and, for this use case, to remember cookies, thus becoming partially stateful.

Please check the detailed procedure in Guzzle Docs. The important thing is that, by instantiating the client with a cookiejar middleware, therefore having the client include it from then on, the first request will remember the server’s set-cookie header, and will send it as every further cookie header, making the server recognize the client as a logged in user. Of course, you could also inspect the first response’s headers yourself and send its value from then on.

There might be other ways, but I can’t think of another right now.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)