太多重定向问题 - 身份验证流程

Too Many Redirects Issue - Authentication Flow

我的认证流程如下: 我在下面设置了身份验证以允许访问。

<?php
session_start();
$username = $_POST["username"];
$password = $_POST["password"];

function check($username, $password){
    $_SESSION['Authenticated'] = true;
    $_SESSION['Expires'] = time() + 3600;
    $_SESSION['username'] = $username;
    header("location: ../index");
    exit;
    };
 };

check($username, $password);
?>

在每个需要身份验证的页面上,我都包括:

<?php
session_start();
require '../scripts/check-auth.php';
?>

调用这个脚本:

<?php
$page = $_SERVER['REQUEST_URI'];
if(isset($_SESSION['Authenticated']) && $_SESSION['Authenticated']){
    if($_SESSION['Expires']< time()){
        $_SESSION["status_code"] = "401";
        header('Location: ../views/login.php');
        exit;   
    }
    $_SESSION['Expires'] = time() + 3600;
    if($page == '/views/login.php'){
        header('Location: ../index.php');
        exit;
    }
} else {
    $_SESSION["status_code"] = "401";
    if($page != '/views/login.php'){
        header('Location: ../views/login.php');
        exit;
    }
};

?>

该流程对于初始身份验证工作正常,但是如果它过期然后重新登录,它会产生重定向过多的错误。 有人可以提供帮助吗?

问题出在 check-auth.php,您需要取消设置变量,因为您无论如何都要将用户重定向到登录页面:

<?php
$page = $_SERVER['REQUEST_URI'];
if(isset($_SESSION['Authenticated']) && $_SESSION['Authenticated']){
    if($_SESSION['Expires']< time()){
        unset($_SESSION['Authenticated']);
        unset($_SESSION['Expires']);
        $_SESSION["status_code"] = "401";
        header('Location: ../views/login.php');
        exit;   
    }
    $_SESSION['Expires'] = time() + 3600;
    if($page == '/views/login.php'){
        header('Location: ../index.php');
        exit;
    }
} else {
    $_SESSION["status_code"] = "401";
    if($page != '/views/login.php'){
        header('Location: ../views/login.php');
        exit;
    }
};

?>

如果您不想取消设置变量,只需删除 unset() 的行并将其替换为以下行:

$_SESSION['Authenticated'] = false;

这应该可以解决问题。