Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use HTTP-AUTH to redirect?

Tags:

http

php

curl

Is there a way to have PHP redirect to a new page, and pass along HTTP-AUTH?

I have been using cURL, as the second example here: Sending basic authentication information via form

Unfortunately, when I do this, the actual URL (as displayed in the browser URL bar) remains the originating PHP's URL, not the target that I'm browsing.

Here is what I've got so far:

<?php

$user = "xyz";
$pass = "abc";
$userpass = $user . ":" . $pass;

$url = "http://website/directory/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $userpass);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if($httpcode == 200){
    header("Authorization: Basic " . base64_encode($userpass));
    echo $result;
}else{
    header("Location: http://website/login.php");
}

?>

I have also tried replacing the tail end of the above:

if($httpcode == 200){
    header("Authorization: Basic " . base64_encode($userpass));
    header("Location: http://website/directory/");
}else{
    header("Location: http://website/login.php");
}

But that fails; it redirects to http://website.xyz/directory, but it does not pass in the user/pass, and I am presented with a login from the server upon arrival.

Technically, the following works. However, I'd much prefer a more graceful solution than passing user/pass inside the HREF:

header("Location: http://" . $userpass . "website/directory/");
like image 529
ltwally Avatar asked Oct 05 '22 12:10

ltwally


1 Answers

Try to pass the Authentication along with the url. Like this:

header('Location: http://username:password@website/directory/');

As base64 is insecure like plain text, it shouldn't be an additional security risk. Browsers will not display the user:pass related part of the url in address bar. But the browser will display a message box (or something else) to let you confirm that you are about to login to this site using username: yourusername

like image 61
hek2mgl Avatar answered Oct 13 '22 12:10

hek2mgl