1

目的

認証されたユーザーのみに在庫管理機能を提供するため。

問題

jQuery ログイン ダイアログを使用してログインを偽装し、資格情報を入力せずに [接続] をクリックすると、Javascript アラートで認証済みと表示されます。

インベントリ セクションに移動すると、管理ボタンが表示されません。それは問題ありませんが、PHP がユーザーを認証済みとして返すのはなぜでしょうか?

認証が正しく行われると、Javascript アラートはまだ認証されていることを示していますが、ページを更新した後に管理ボタンが表示されません。なにが問題ですか?

コードサンプル

サイトのエントリ ポイント:index.php

<?php 
require_once "security/logout.php";
logout();
session_start();
$now = time();
$_SESSION["authenticated"] = false;
$_SESSION["expires"] = $now + strtotime("20 minutes");
$_SESSION["last_activity"] = $now;
?>

logout.php

<?php
function logout() {
    $sid = session_id();
    if (empty($sid)) session_start();
    session_unset();
    session_destroy();
    session_write_close();
    session_regenerate_id(true);
}
?>

authenticated.php

このファイルはrequire_once、セッションを設定する必要があるすべての php ファイルと同様に使用されます。session_start()すべての単一の PHP ファイルに使用するのと少し似ています。

<?php 
require_once "security/logout.php";

$sid = session_id();
if (empty($sid)) session_start();

if (!isSet($_SESSION["expires"]) 
    || !isSet($_SESSION["authenticated"]) 
    || !isSet($_SESSION["last_activity"])
    || $_SESSION["expires"] < time()) {
    logout();
    $now = time();
    $_SESSION["authenticated"] = false;
    $_SESSION["last_activity"] = $now;
    $_SESSION["expires"] = $now + strtotime("20 minutes");
}
?>

login.php

<?php
require_once "security/authenticated.php";

require_once "data/data_access.php";

$userName = "";
$password = "";

if (isSet($_REQUEST["userName"])) $userName = $_REQUEST["userName"];
if (isSet($_REQUEST["password"])) $password = $_REQUEST["password"];

if (isAuthenticUser($userName, $password)) {
    session_regenerate_id(true);    
    $now = time();
    $_SESSION["authenticated"] = true;
    $_SESSION["last_activity"] = $now;
    $_SESSION["expires"] = $now + strtotime("20 minutes");
} else $_SESSION["authenticated"] = false;

// The line below is the server response reported by the Javascript alert().
echo $_SESSION["authenticated"] ? 'true' : 'false';
?>

編集#1追加data/data_access.php

function isAuthenticUser($userName, $password) {
    $sql = "select password from jmsports.users where login = :login";
    $cnx = createAndOpenDatabaseConnection();
    $stmt = $cnx->prepare($sql);
    $stmt->bindParam(":login", $userName);
    $stmt->execute();
    $result = $stmt->fetch();
    $isAuthentic = $result["password"] === $password;

    // Bool:strictBool only ensures that only true or false is returned.
    return Bool::strictBool($isAuthentic);
}

編集 #2サーバー側でボタンを表示/非表示にするコードを追加しました。

inventory-section.php

// This line below states that my authenticated session variable is false.
file_put_contents("debug.txt", $_SESSION["authenticated"] ? "true" : "false", FILE_APPEND);

<div id="newButtonDiv" style="text-align: center;">
<?php if ($_SESSION["authenticated"]):  ?>
    <button id="newButton">Add New Item</button>
<?php endif; ?>
</div>

どんな助けでも感謝します。ありがとう!

4

1 に答える 1