seba1rx/sessionadmin

php session admin,具有URL控制和防止劫持的安全功能

dev-main 2024-01-26 18:37 UTC

This package is auto-updated.

Last update: 2024-09-26 19:55:27 UTC


README

简单的PHP会话管理器,实现防止劫持的安全功能

需要PHP 8

使用以下命令安装:composer require seba1rx/sessionadmin:dev-master

如果您收到消息“无法找到与您的最小稳定性(稳定)匹配的package seba1rx/sessionadmin版本”,则在安装前请将"minimum-stability": "dev"添加到您的composer.json文件中

用法

在每个PHP页面中,像使用session_start()一样调用activateSession()方法

为了使用这个类,您可以使用Seba1rx\MySessionAdmin类,或者您可以创建自己的类来扩展Seba1rx\SessionAdmin类

该类有两个公共方法

activateSession()createUserSession()

您可以在/demo中找到一个工作的演示,该演示显示了一个实现该类的基本网站,或者您可以将此存储库克隆到本地开发环境中以尝试演示。

此类对于具有公开内容但仅登录后才能访问受限内容的网站非常有用。

功能

  • 为访客和用户创建会话
  • 命名会话
  • 每次请求有3%的概率重新生成会话ID
  • 防止劫持
  • 为访客定义允许的URL数组,当用户登录时根据系统配置可以扩展
  • 在过时的请求上销毁会话

以下是一些屏幕截图

Index, public content

page2, login, public content

private content

以下是一个演示认证器

require('../vendor/autoload.php');

use Seba1rx\MySessionAdmin;

$rxSessionAdmin = new MySessionAdmin(
    [
        "sessionLifetime" => 3600,
        "allowedURLs" => ["index.php", "page2.php"],
        "keys" => [
            "some_key" => "some_value",
            "foo" => "bar",
        ],
   ]
);
$rxSessionAdmin->activateSession();

// this scripts simulates an authentication, you should implement your own validation

$validationResponse = [
    'ok' => false,
    'msg' => null,
];


if(
    isset($_POST["useremail"]) && !empty($_POST["useremail"]) && isset($_POST["userpassword"]) && !empty($_POST["userpassword"])
    // no other validation so you can use any user/email in this demo
){
    // lets assume we query the system database and the data matching the credentials is the following
    $data = [
        "id" => 123,
        "name" => "Sebastian",
        "nickname" => "seba1rx",
        "avatar" => "cat-space.gif",
        "birthDate" => "1985-05-21",
        "country" => "Chile",
        "email" => $_POST["useremail"]
    ];

    // up to now we are in guest mode... lets call the method to create the user session
    $rxSessionAdmin->createUserSession($data['id']);

    // since $_SESSION is open, there is no point in encapsulating the data with get and set... lets add the data to SESSION['data']
    foreach($data AS $dataName => $dataValue){
        $_SESSION['data'][$dataName] = $dataValue;
    }

    // here you woud iterate to add allowed urls according to assigned profile
    // foreach($ProfileAllowedUrls AS $url){
    //    $_SESSION['allowedUrl'][] = $url;
    // }

    $validationResponse['ok'] = true;
    $validationResponse['msg'] = 'Wellcome '.$_SESSION['data']['name'];

}else{
    $validationResponse['ok'] = false;
    $validationResponse['msg'] = 'Complete the form fields!';
}

echo json_encode($validationResponse);