vielhuber/simpleauth

简单的PHP身份验证库。

1.3.7 2023-01-10 00:47 UTC

README

simpleauth是一个基于PHP的简单身份验证库。

它利用

  • JSON Web Tokens
  • bcrypt密码
  • 完整的API

安装

使用composer一次性安装

composer require vielhuber/simpleauth

现在,在您的public目录下新建一个名为auth的文件夹,并创建以下文件:

/auth/index.php

<?php
require_once __DIR__ . '/../vendor/autoload.php';
use vielhuber\simpleauth\simpleauth;
$auth = new simpleauth(__DIR__ . '/../.env');
if (php_sapi_name() !== 'cli') {
    $auth->api();
} elseif (@$argv[1] === 'migrate') {
    $auth->migrate();
} elseif (@$argv[1] === 'seed') {
    $auth->seed();
}

/auth/.htaccess

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /auth/index.php [L,QSA]

/.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=simpleauth
DB_USERNAME=root
DB_PASSWORD=root
JWT_TABLE=users
JWT_LOGIN=email
JWT_TTL=30
JWT_SECRET=I2hkRtw6t8Yg9Wvlg99Nij23Bvdm0n0L4UPkVC33a7rMo5EQGlnIv79LAOIMIxE
BASE_URL=http://simpleauth.local.vielhuber.de

如果您想迁移和填充数据,只需运行

php auth/index.php migrate
php auth/index.php seed

然后您就应该完成了(创建了一个测试用户david@vielhuber.de,密码为secret)。
您现在可以使用以下路由进行完全的身份验证。
如果您想通过用户名而不是电子邮件进行身份验证,只需将JWT_LOGIN更改为username

路由

以下路由将自动提供

进一步使用

您可以在自己的应用程序中使用以下函数(它们不需要任何数据库查询)

require __DIR__ . '/vendor/autoload.php';
use vielhuber\simpleauth\simpleauth;
$auth = new simpleauth(__DIR__ . '/.env');

$auth->isLoggedIn();
$auth->getCurrentUserId();

前端

如果您需要一个与simpleauth无缝工作的精美前端库,请尝试jwtbutler