Basic Authentication with PHP gives an endless loop

試著忘記壹切 提交于 2019-12-01 01:25:33

问题


For some reason I can't get Basic Authentication to work using PHP on my server. I am using the exact code from the manual page:

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>

However, when I run it, I can never get beyond the prompt.

If I put this same code on my other server, it works fine.

Does anyone know what could be causing this? Both servers are WAMP stacks and Apache has the auth_basic_module enabled. The PHP.ini files are practically identical as well.

I glanced at the headers and after I enter my username/password, there is the "Authorization: Basic XXXXXX" header being sent.


回答1:


This depends on the used PHP interface. The environment variable PHP_AUTH_USER is only used for mod_php and if Apache helped.

If you initialize the authorization from the script, then you have to look for the HTTP_AUTHORIZATION header, and decode and split it up yourself. Look at this comment: http://www.php.net/manual/en/features.http-auth.php#94349

For FastCGI setups or suexec invokations you might not even have that header present in the environment variables. It's filtered out as security precaution. The common workaround is to rewrite the header using a .htaccess rule:

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Thus it becomes available with mixed-case as $_SERVER["HTTP_Authorization"].



来源:https://stackoverflow.com/questions/4928228/basic-authentication-with-php-gives-an-endless-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!