php 如何使用 Guzzle 进行 HTTP 基本身份验证?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30970736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:09:34  来源:igfitidea点击:

How do i do HTTP basic authentication using Guzzle?

phphttpbasic-authenticationguzzle

提问by Gopi K Mishra

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.

我想使用 Guzzle 进行基本访问身份验证,而且我对编程非常陌生。我不知道该怎么做。我尝试使用 curl 来做到这一点,但我的环境需要使用 guzzle。

回答by ffflabs

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

如果您使用的是Guzzle 5.0 或更新版本文档说基本身份验证是使用 auth 参数指定的:

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

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

请注意,如果您使用的是Guzzle 3.0 或更早版本,则语法会有所不同。构造函数不同,您还需要在请求上显式使用该方法才能获得响应:send

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

回答by mnv

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

除了@amenadiel 的回答。有时在构造函数中指定身份验证参数很方便:

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

Then every request will use this default auth parameters.

然后每个请求都将使用这个默认的 auth 参数。

回答by bourgeois247

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

当我使用 Guzzlev6 并使用来自@amenadiel 的建议时,这种方法有效。当你使用 curl 时,你的语法看起来像

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

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:

在幕后,它实际上需要[email protected]:password”位,base64 对其进行编码,并发送带有编码值的“授权”标头的请求。对于这个例子,这将是:

Authorization: Basic c29tZW9uZUBnbWFpbC5jb206cGFzc3dvcmQ=

授权:基本 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

来自@amenadiel 的建议附加了一个“auth: username,password”标头,因此,我的身份验证一直失败。要成功实现这一点,只需在实例化 Guzzle Client 请求时制作标头,即

$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,

这将像 curl 那样附加标题,并且您尝试连接的任何服务都将停止对您大喊大叫,

Cheers.

干杯。

回答by Eric Gruby

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

根据Guzzle 6文档,您可以像这样简单地使用基本授权执行请求:

$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.

注意:您根本不需要使用 base64_encode() ,因为它在请求之前已经这样做了。

I've tested and it works :)

我已经测试过了,它有效:)

See more at: Guzzle 6 Documentation

查看更多:Guzzle 6 文档

回答by Baach

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

回答by Agu Dondo

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

根据@bourgeois247 关于 base64 编码的说法,以下内容在 Guzzle 6 上非常适合我:

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

回答by HRoux

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)

如果你和 symfony 一起使用,你也可以在你的配置文件中定义它(config/packages/eight_points_guzzle.yaml 用于 symfony4 或 flex 或 config.yml 用于其他版本)

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

请参阅:https: //packagist.org/packages/eightpoints/guzzle-bundle