Xác Thực Danh Tính Trong PHP

Trong bài viết này, chúng ta sẽ thảo luận về các phương pháp xác thực danh tính thường được sử dụng trong ứng dụng web PHP. Các phương pháp này bao gồm HTTP Basic Authentication, Cookie Authentication, Session-Cookie Authentication và Token-Session Authentication.

1. HTTP Basic Authentication

Phương pháp xác thực này yêu cầu người dùng nhập tên đăng nhập và mật khẩu mỗi khi truy cập vào tài nguyên hạn chế. Dưới đây là một ví dụ đơn giản về cách triển khai:

  • Tạo một form đăng nhập:
<html>
<head>
    <title>Đăng Nhập</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="login-form">
        <h2>Đăng Nhập Quản Trị</h2>
        <form action="auth_basic.php" method="POST">
            <div>
                <label>Tên Đăng Nhập:</label>
                <input type="text" name="user" required>
            </div>
            <div>
                <label>Mật Khẩu:</label>
                <input type="password" name="pass" required>
            </div>
            <button type="submit">Đăng Nhập</button>
        </form>
        <?php
        if (isset($_GET['err'])) {
            echo '<script>alert("Tên đăng nhập hoặc mật khẩu không đúng!");</script>';
            echo '<script>history.replaceState(null, null, window.location.pathname);</script>';
        }
        ?>
    </div>
</body>
</html>
  • Tạo file cấu hình kết nối cơ sở dữ liệu:
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '123456');
define('DB_NAME', 'auth_db');

$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$conn) {
    die("Kết nối thất bại: " . mysqli_connect_error());
}
?>
  • Xử lý xác thực:
<?php
include 'config.php';

$user = $_POST['user'];
$pass = $_POST['pass'];

$sql = "SELECT * FROM users WHERE username = '$user' AND password = '$pass'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    header('Location: dashboard.php');
} else {
    header('Location: login.php?err=1');
}
mysqli_close($conn);
?>

2. Cookie Authentication

Khi người dùng đăng nhập thành công, máy chủ tạo ra một cookie chứa thông tin xác thực và gửi nó đến trình duyệt. Mỗi lần truy cập tài nguyên hạn chế, trình duyệt sẽ gửi lại cookie đó.

  • Xử lý xác thực và thiết lập cookie:
<?php
include 'config.php';

$user = $_POST['user'];
$pass = $_POST['pass'];

$sql = "SELECT * FROM users WHERE username = '$user' AND password = '$pass'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    setcookie('auth_user', $user, time() + 86400, '/');
    header('Location: dashboard.php');
} else {
    header('Location: login.php?err=1');
}
mysqli_close($conn);
?>
  • Kiểm tra cookie trên trang quản trị:
<?php
if (isset($_COOKIE['auth_user']) && $_COOKIE['auth_user'] === 'admin') {
    echo "Chào mừng bạn đến với trang quản trị.";
} else {
    header('Location: login.php?err=1');
}
?>

3. Session-Cookie Authentication

Thay vì lưu trữ thông tin xác thực trực tiếp trong cookie, phiên làm việc (session) được sử dụng để lưu trữ thông tin. Mỗi lần truy cập, trình duyệt gửi mã phiên làm việc (session ID) thay vì thông tin xác thực.

  • Xử lý xác thực và khởi tạo phiên:
<?php
session_start();
include 'config.php';

$user = $_POST['user'];
$pass = $_POST['pass'];

$sql = "SELECT * FROM users WHERE username = '$user' AND password = '$pass'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    $_SESSION['auth_user'] = $user;
    header('Location: dashboard.php');
} else {
    header('Location: login.php?err=1');
}
mysqli_close($conn);
?>
  • Kiểm tra phiên trên trang quản trị:
<?php
session_start();
if (isset($_SESSION['auth_user']) && $_SESSION['auth_user'] === 'admin') {
    echo "Chào mừng bạn đến với trang quản trị.";
} else {
    header('Location: login.php?err=1');
}
?>

4. Token-Session Authentication

Bên cạnh việc sử dụng phiên, phương pháp này thêm một token ngẫu nhiên vào mỗi yêu cầu để ngăn chặn tấn công lặp lại.

  • Tạo form đăng nhập với token:
<html>
<head>
    <title>Đăng Nhập</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <?php
    session_start();
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    ?>
    <div class="login-form">
        <h2>Đăng Nhập Quản Trị</h2>
        <form action="auth_token.php" method="POST">
            <div>
                <label>Tên Đăng Nhập:</label>
                <input type="text" name="user" required>
            </div>
            <div>
                <label>Mật Khẩu:</label>
                <input type="password" name="pass" required>
            </div>
            <input type="hidden" name="token" value="<?php echo $_SESSION['csrf_token']; ?>">
            <button type="submit">Đăng Nhập</button>
        </form>
        <?php
        if (isset($_GET['err'])) {
            echo '<script>alert("Tên đăng nhập hoặc mật khẩu không đúng!");</script>';
            echo '<script>history.replaceState(null, null, window.location.pathname);</script>';
        }
        ?>
    </div>
</body>
</html>
  • Xử lý xác thực với kiểm tra token:
<?php
session_start();
include 'config.php';

$user = $_POST['user'];
$pass = $_POST['pass'];
$token = $_POST['token'];

$sql = "SELECT * FROM users WHERE username = '$user' AND password = '$pass'";
$result = mysqli_query($conn, $sql);

if ($token !== $_SESSION['csrf_token']) {
    header('Location: login.php?err=1');
} elseif (mysqli_num_rows($result) > 0) {
    $_SESSION['auth_user'] = $user;
    header('Location: dashboard.php');
} else {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    header('Location: login.php?err=1');
}
mysqli_close($conn);
?>

Thẻ: php authentication Security Session Cookie

Đăng vào ngày 27 tháng 5 lúc 00:25