How do I do HTTP basic authentication using Guzzle?

PhpHttpBasic AuthenticationGuzzle

Php Problem Overview


I want to do basic access authentication using Guzzle and I am very new to programming. I have no clue what to do. I tried to do this using curl but my environment requires using guzzle.

Php Solutions


Solution 1 - Php

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 - Php

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 - Php

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 - Php

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

Solution 5 - Php

$response = $client->request( 'GET', 'your_url', [
					'auth'    => [
						'your_username',
                        'your_password'
					],
					'headers' => [
						'if you want to pass something in the headers'
					]
				]
			);

Solution 6 - Php

You can also configure the auth params when instantiating the client instead of adding it to each request:

$this->client = new \GuzzleHttp\Client([                                                                                                                                             
    'base_uri' => $this->endpoint,                                                                                                                                                   
    'headers' => [                                                                                                                                                                   
        'Authorization' => ['Basic'.base64_encode($this->username.':'.$this->password)],                                                                                                 
    ],                                                                                                                                                                               
]);

Here are the various doc links for Guzzle 6:

Solution 7 - Php

According to what @bourgeois247 said about base64 encoding, the following worked perfectly for me on Guzzle 6:

$client = new Client();
$credentials = base64_encode('username:password');
$response = $client->post('url',
		[
			'headers' => [
				'Authorization' => 'Basic ' . $credentials,
		    ],
		]);

Solution 8 - Php

If you use it with symfony, you can also define it in your configuration file (config/packages/eight_points_guzzle.yaml for symfony4 or flex or config.yml for the other version)

In your configuration file :

eight_points_guzzle:
    clients:         
        your_service:
            # Write here the host where to do requests
            base_url: "yourURL"

            options:
                timeout: 30
                auth:
                    - yourLogin     # login
                    - yourPassword # password
            plugin: ~

Then, in your service, controller, etc....

$client  = $this->getContainer()->get('eight_points_guzzle.client.your_service');
$response = $client->get('yourRoute');

See : https://packagist.org/packages/eightpoints/guzzle-bundle

Solution 9 - Php

 $client = new Client();
    $response = Http::withBasicAuth($username,$password)
    ->post($url);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGopi K MishraView Question on Stackoverflow
Solution 1 - PhpffflabsView Answer on Stackoverflow
Solution 2 - PhpNickView Answer on Stackoverflow
Solution 3 - Phpbourgeois247View Answer on Stackoverflow
Solution 4 - PhpEric GrubyView Answer on Stackoverflow
Solution 5 - PhpBaachView Answer on Stackoverflow
Solution 6 - PhpkjonesView Answer on Stackoverflow
Solution 7 - PhpAgu DondoView Answer on Stackoverflow
Solution 8 - PhpHRouxView Answer on Stackoverflow
Solution 9 - PhpShafi AsharafView Answer on Stackoverflow