[英]PHP and Basic Auth
我知道這個話題有很多問答,到目前為止沒有任何對我有用。
我使用 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 配置或 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>
有什么建議嗎?
您是否嘗試在 xhr 請求中添加標頭? 喜歡:
client.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.