【问题标题】:PHP and Basic AuthPHP 和基本身份验证
【发布时间】:2021-01-28 04:37:03
【问题描述】:

我知道这个主题有很多问答,到目前为止对我没有任何帮助。

我使用 Javascript/XMLHttpRequest 从我的 PC 向我的服务器(Ubuntu/Apache/PHP 7.4)发出跨站点 HTTP 请求:

var client = new XMLHttpRequest();
client.open('GET', src, true, username, password);
client.withCredentials = true;

我的 PHP 脚本发送的标头:

function print_headers($content_type) {
       $referer = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : '*';
       
       if (substr($referer, strlen($referer) - 1) == '/') {
           $referer = substr($referer, 0, strlen($referer) - 1); 
       }
       
       header("Access-Control-Allow-Origin: " . $referer);
       header("Access-Control-Allow-Credentials: true");
       header("Access-Control-Allow-Methods: GET");
       header("Access-Control-Allow-Headers: authorization,content-type");
       header($content_type);
}

它在没有基本身份验证的情况下工作,对于基本身份验证,我无法从 PHP_AUTH_USER 和 PHP_AUTH_PW 获取用户名/密码(它们是空的):

$username = $_SERVER['PHP_AUTH_USER'];

$password = $_SERVER['PHP_AUTH_PW'];

通常建议在 Apache config 或 htaccess 中使用此 RewriteRule:

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

在 PHP 中:

list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':' , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

它不起作用。我网站的 Apache 配置:

<Directory "/var/www/my.site.com/">
    RewriteEngine on
    #RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
    RewriteBase /
    RewriteRule ^(?!admin).*$ index.php
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
    SSLOptions +StdEnvVars
    SSLRequireSSL
</Directory>

有什么建议吗?

【问题讨论】:

    标签: javascript php basic-authentication


    【解决方案1】:

    您是否尝试将标头添加到您的 xhr 请求中?喜欢:

    client.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
    

    【讨论】:

    • 我添加了该行,Chrome 显示:“已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态”
    • 那么服务器端的cors配置有问题,试试把header改成header("Access-Control-Allow-Origin: *");
    猜你喜欢
    • 2011-01-28
    • 1970-01-01
    • 2021-07-29
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多