How do I do HTTP basic authentication using Guzzle?

前端 未结 8 1268
无人及你
无人及你 2020-12-24 00:11

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

相关标签:
8条回答
  • 2020-12-24 01:13

    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 someone@gmail.com:password http://service.com

    behind the scenes it actually takes the "someone@gmail.com: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('someone@gmail.com: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.

    0 讨论(0)
  • 2020-12-24 01:14

    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

    0 讨论(0)
提交回复
热议问题