簡體   English   中英

使用來自官方文檔的PHP代碼進行HTTP身份驗證無法正常工作

[英]HTTP authentication with PHP code from official docu not working properly

我需要網站的身份驗證方法,我在官方手冊上找到了這篇文章並進行了嘗試。

<?php
$realm = 'Restricted area';

//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');


if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Digest realm="'.$realm.
           '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');

    die('Text to send if user hits Cancel button');
}

if  // analyze the PHP_AUTH_DIGEST variable
(
    !($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST']))   ||
    !isset($users[$data['username']])
)
{
    die('Wrong Credentials!');
}    

// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

if ($data['response'] != $valid_response)
    die('Wrong Credentials!');

// ok, valid username & password
echo 'You are logged in as: ' . $data['username'];


// function to parse the http auth header
function http_digest_parse($txt)
{
    // protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();
    $keys = implode('|', array_keys($needed_parts));

    preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? $m[3] : $m[4];
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    <p>Test</p> 
</body>
</html>

但是,如果我無法輸入正確的憑據,那么我將獲得Wrong Credentials! 即使重新加載后也一直沒有任何提示。 這是什么原因造成的,我該如何解決?

瀏覽器將根據新請求再次發送給定的憑據。 要向瀏覽器詢問新的憑據,您需要重新發送WWW-Authenticate標頭。 die()之前。

像這樣 :

if  // analyze the PHP_AUTH_DIGEST variable (
    !($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST']))   ||
    !isset($users[$data['username']]) ) {
    header('WWW-Authenticate: Digest realm="'.$realm.
           '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
        die('Wrong Credentials!');
}

if ($data['response'] != $valid_response) {
    header('WWW-Authenticate: Digest realm="'.$realm.
               '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
    die('Wrong Credentials!');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM