PHP 身份验证

Sheeraz Gul 2024年2月15日
  1. 在 PHP 中使用基本 HTTP 身份验证对用户进行身份验证
  2. 在 PHP 中使用 Digest HTTP 身份验证对用户进行身份验证
PHP 身份验证

HTTP 身份验证向客户端发送特殊的 HTTP 标头,并要求提供身份验证代码以访问该页面。

它是一种 PHP 内置方法,用于验证用户是否执行特定任务。PHP 有两种 HTTP 身份验证方法,BasicDigest

HTTP 身份验证将生成一个弹出窗口来询问身份验证信息。

它使用数组 $_SERVER 变量、PHP_AUTH_USERPHP_AUTH_PW 对用户进行身份验证,并使用 AUTH_TYPE 设置身份验证类型。

在 PHP 中使用基本 HTTP 身份验证对用户进行身份验证

基本 HTTP 身份验证使用非加密 PHP base64 编码;这就是为什么它应该只在提供 HTTPS 等安全性时使用。

这些证券称为传输层证券。

<?php

if( ( isset($_SERVER['PHP_AUTH_USER'] ) && ( $_SERVER['PHP_AUTH_USER'] == "admin" ) ) AND ( isset($_SERVER['PHP_AUTH_PW'] ) && ( $_SERVER['PHP_AUTH_PW'] == "password" )) )

{

    echo(" Hello ".$_SERVER['PHP_AUTH_USER']."! <br>\n");

}
else
{
    // These headers will cause the browser to ask for authentication information
    header('WWW-Authenticate: Basic realm="This page is only authorized to registered users"');
    header('HTTP/1.0 401 Unauthorized');

    //This text will be shown after several failed attempts, or you cancel the pop-up box.
    echo"Protected by HTTP Authentication <br>";
	echo "Use <b>admin</b> for the username, and <b>password</b> for the password to enter";
    }
?>

此代码将生成一个弹出框并询问用户名和密码。

如果输入正确的信息,你将可以访问页面,如果输入错误,代码将重定向几次,最后打印失败消息。

用户名是 admin,密码是 password

输出:

PHP 函数警告消息

If the information is correct:
"Hello admin!" 
If the information is failed:
"Protected by HTTP Authentication"
"Use admin for the username, and password for the password to enter."

在 PHP 中使用 Digest HTTP 身份验证对用户进行身份验证

摘要认证通过对信息使用散列函数来使用加密。

此信息包括用户信息、HTTP 方法、服务器提供的 nonce 值和请求的 URL;它比基本 HTTP 身份验证更安全,因为信息是加密的。

// User authentication info
$auth_info = array('user1' => 'pass1', 'user2' => 'pass2');

// First of all check PHP_AUTH_DIGEST variable, if it is empty the header will redirect the page to pop up box.
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
    header('WWW-Authenticate: Digest realm="Restricted area",qop="auth",nonce="'.uniqid().'",opaque="'.md5("Restricted area"));
    header('HTTP/1.1 401 Unauthorized');

    exit('You cancelled the authentication');
}

// it is required to check the Digest Authentication Variable first before converting the information to md5

if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($auth_info[$data['username']])){
    exit('The authentication information entered is not correct!');
}

// generating the valid authentication response using the client info and server request method

$auth_hash1 = md5($data['username'] . ':Restricted area:' . $auth_info[$data['username']]);
$auth_hash2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$auth_response = md5($auth_hash1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$auth_hash2);

if ($data['response'] != $auth_response){
    exit('The authentication information entered is not correct!');
}
else{
// if authentication response matches the info 
    echo 'Welcome ' . $data['username'].' you are an authenticated user';
}

// The function below is from the official PHP manual, https://www.php.net/manual/en/features.http-auth.php. It is used to parse the HTTP digest.
function http_digest_parse($txt)
{
    
    $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;
}

上面的代码显示了应用摘要 HTTP 身份验证方法的过程。你可以使用 PHP 手册中的 http_digest_parse() 函数并使用它来解析 HTTP Digest 身份验证。

输出将与基本类似,但更安全。有两个用户,user1user2

有两个密码,分别是 pass1pass2。你可以输入任何信息并登录。

输出:

PHP 函数警告消息

If the information is correct:
"Welcome admin you are an authenticated user"
If the information is failed:
"The authentication information entered is not correct!"
If you cancel the pop up:
"You cancelled the authentication"
作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook