How can I send basic authentication with request?
Hi there
I am trying to set up a proxy where I pass on the path of the request and send Basic Authentication headers along.
How could I achieve this? I thought something like this should work:
$response = $proxy
->forward($request)
->filter(function ($request, $response, $next) {
$method = 'GET';
$uri = 'http://cms.local.test/api/pages/';
$request = new GuzzleHttp\Psr7\Request(
$method,
$uri,
[
'auth' => ['myusername', 'mypassword]
'Content-Length' => 30000, // a random number? How could I fix this issue that a length is required?
],
$request->getBody()
);
// Proceed with the rest
$response = $next($request, $response);
return $response;
})
->to('http://cms.local.test/api/pages/');
// Output response
(new Zend\HttpHandlerRunner\Emitter\SapiEmitter)->emit($response);
If I run this I get 'Unauthenticated', which I would get if I request the given URL without a password and without a username.
Interestingly, if I change the user to a wrong username, I do get The user \"mywrongusername\" cannot be found.
So I assume that the whole auth headers are NOT sent along.
How could I send Basic auth to the final URL?
Also I had the problem that I when I create a new guzzle request that I have to repeat the request URL. Is there a smarter way to do that?
Thank you for your help. cheers
PS:If I leave out the Content-Length part I get an error that this is required. What should I set there?
$proxy->filter(new RemoveEncodingFilter())->filter(function ($request, $response, $next) use ($path) {
$username = 'admin';
$password = 'admin';
$request = $request->withHeader('Authorization', "Basic " . base64_encode("$username:$password"));
$response = $next($request, $response);
return $response;
});