如何在基本身份验证中显示错误消息?

时间:2020-02-19 12:35:32

标签: php authentication basic-authentication

我使用PHP实现了以下基本身份验证:

if ((isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER']=='') || (isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW']=='')) {
    header('WWW-Authenticate: Basic realm="Authentification"');
    $UsrId = $objLDAP->authenticateUser();
    die();
} elseif (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    $UsrId = $objLDAP->authenticateUser($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
}else{ 
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo '<script>window.location.reload();</script>';
    //$UsrId = $objLDAP->authenticateUser();
    //$smarty->display($templates['budWithoutAnyAccess']);
    die();
}
if ($pUser){
 //coding
}else{
    header('HTTP/1.1 401 Authorization Required');
    header('WWW-Authenticate: Basic realm="Access denied"');
    $UsrId = $objLDAP->authenticateUser();
}

它会打开登录弹出窗口。

如果用户提供了错误的凭据,我可以在页面上显示错误消息,但是在刷新页面时,它也应该打开“身份验证”登录弹出窗口。

在取消时,我也要显示消息,并在刷新时,它应打开“身份验证”登录弹出窗口。

我该怎么做?

谢谢你, 特伦蒂

1 个答案:

答案 0 :(得分:-1)

请检查一下!

 if (!isset($_SERVER['PHP_AUTH_USER']))
    {
        header('WWW-Authenticate: Basic realm="Sally Port"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Click <a href="login.php">here</a> to reload';
        exit;
    }

    if(checkLDAPUser($ldapServername))
    {
        // If ldap authentican is successful then redirect the user to gateway.php
        header("location:gateway.php");
    }
    else
    {
        //Clear global variables.
        unset($_SERVER['PHP_AUTH_USER']);
        unset($_SERVER['PHP_AUTH_PW']);

    //  If the password is incorrect, show popup until the password is correct.
        while(checkLDAPUser($ldapServername)!=1)
        {
            unset($_SERVER['PHP_AUTH_USER']);
            unset($_SERVER['PHP_AUTH_PW']);
            header('WWW-Authenticate: Basic realm="Sally Port"');
            header('HTTP/1.0 401 Unauthorized');
            echo 'Click <a href="login.php">here</a> to reload';
            exit;
        }
    }
function checkLDAPUser($ldapServername)
{
    $username=$_SERVER['PHP_AUTH_USER'];
    $password=$_SERVER['PHP_AUTH_PW'];

    //$adServer = "ldap.".$ldapServername.".com";
    $adServer = "ldap://bchq-dc-v1.blackcreek.local";
    $ldap = ldap_connect($adServer);
if($ldap)
{WriteLog("LDAP connected");

}
else
{WriteLog("LDAP Failed");

}
    $ldaprdn = "cn=read-only-admin,dc=example,dc=com";
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
    $bind = @ldap_bind($ldap, $ldaprdn, $password);             
    //Set up session if connect is successful.
    if($bind)
    {
        return 1;
    }
    else
    {console.log("LDAP Username and Passwords are incorrect");

        return 0;
    }
}
相关问题