2015-06-22 194 views
32

我想使用Guzzle進行基本的訪問認證,而且我對編程非常陌生。我不知道該怎麼做。我試圖使用curl來做到這一點,但我的環境需要使用guzzle。我如何使用Guzzle進行HTTP基本身份驗證?

+7

你確實應該嘗試任何代碼你試過粘貼,以提高你得到一個有意義的答案的機會。只要說出你的需要和無知就會得到你的低估:( – amenadiel

回答

51

如果您使用狂飲5.0或更新版本the docs說基本身份驗證使用auth參數指定:

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

請注意,syntax is different如果你使用狂飲3.0或更早版本。構造函數是不同的,你還需要明確地使用在要求send方法得到迴應:

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

這時候我用Guzzlev6和使用來自@amenadiel建議力的工作。當您使用捲曲,你的語法看起來是這樣的

捲曲-u [email protected]:密碼http://service.com

幕後實際發生的[email protected] :密碼「位,base64對它進行編碼,並將請求與」授權「標頭一起發送。對於這個例子,這將是:

授權:基本c29tZW9uZUBnbWFpbC5jb206cGFzc3dvcmQ =

從@amenadiel諮詢所​​附的「AUTH:用戶名,密碼」頭,因此,我的身份驗證保持失敗。要成功做到這一點,只是手藝當你實例化一個狂飲客戶端請求的報頭,即

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

這將追加爲捲曲會和什麼服務,你試圖連接到將停止在吼你的頭,

乾杯。

7

除了@amenadiel的答案。有時在構造函數中指定auth參數:

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

然後每個請求都會使用這個默認的auth參數。

+3

而對於舊''''guzzlehttp/guzzle「:」5.2.0「''' 你應該通過'''''defaults'=> [ ' auth'=> ['username','password'] ]]''' –

2

根據什麼@ bourgeois247說,大約base64編碼,下面完全爲我工作在狂飲6:

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

按照狂飲文檔,你可以用這樣簡單的基本授權的請求:

try{ 
    $res = $client->request(
    'POST', /*instead of POST, you can use GET, PUT, DELETE, etc*/ 
    'URL_GOES_HERE', 
    [ 
     'auth' => ['username', 'password', 'basic'] /*if you don't need to use a password, just leave it null*/ 
    ] 
); 
    echo $res->getStatusCode(); 
    echo $res->getHeader('content-type'); 
    $res->getBody(); 
}catch(Exception $e){ 
    echo $e->getMessage(); 
} 

注:你並不需要在所有使用BASE64_ENCODE()。

我測試和工程:)

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