semibreve/minim

该包已被废弃,不再维护。未建议替代包。

PHP中最小单用户认证。

v1.6 2017-03-08 10:03 UTC

This package is not auto-updated.

Last update: 2024-02-17 17:54:55 UTC


README

PHP中最小单用户认证。

Logo

有时候,你会构建一个需要

  • 无数据库运行
  • 只有管理员后端
  • 仅由一个用户访问

Minim就是为此目的而设计的;它是一个安全、单用户认证系统,不会做诸如泄露用户密码(或将密码以明文形式存储)或在不安全(非HTTPS)连接上运行(除非您希望如此)等愚蠢的事情。

安装

使用Composer安装Minim,如下所示

composer require semibreve/minim

或者,如果您使用PHAR(确保php.exe可执行文件位于您的PATH中)

php composer.phar require semibreve/minim

配置

Minim将要求您创建一个类似于以下内容的配置文件

# Don't commit this file to source control, it contains your secret settings.

admin_email: me@example.com # The e-mail address of the user, used as a username.
admin_password_hash: $2y$10$x8.kXrWv4lXFpObosuwQ0uoiQAUeFAlEL.oi0tN5pnM.72hoK9e8K # The user's password hash.
secret_key: 7WCPTI3of3cp # The secret key the application uses for symmetric encryption
token_length: 32 # The length, in bytes, of any generated authentication tokens.
token_ttl: 1200 # The time to live for authentication tokens, in seconds.
cookie_name: minim_auth # The name of the authentication cookie.
session_file_name: /var/www/minim/token.dat # The name of the session file on-disk.
cookie_ssl_only: false # Whether or not cookies are enabled for HTTPS only. If enabled, non-HTTPS requests will fail.
cookie_http_only: true # Whether to restrict cookies to HTTP only and disallow access by client-side script.

上述文件指定了一些默认凭据

Email: me@example.com
Password: demo

这些凭据必须在生产之前更改,因此您需要执行以下操作

  • 将上面的示例配置文件复制到您的项目中。确保它被版本控制系统忽略。
  • 在您最喜欢的文本编辑器中打开它。
  • admin_email字段更改为您的电子邮件地址
  • admin_password_hash字段更改为您选择的密码的bcrypt散列。使用捆绑的minim-genhash实用程序生成散列,方法是在项目根目录中调用php vendor/bin/minim-genhash <password>
  • secret_key字段更改为至少12个字符的随机字符串。
  • salt字段更改为至少12个字符的随机字符串。
  • token_length字段的默认值32对于大多数应用程序来说是足够的。
  • token_ttl字段的默认值1200秒(20分钟)对于大多数应用程序来说是足够的。
  • session_file_name字段更改为Minim可以读取和写入的、位于服务器上可写文件的绝对路径,但服务器不会提供。
  • 如果您正在通过HTTPS运行,则将cookie_ssl_only字段更改为true。如果您不是,请仔细审查您的应用程序,并问自己为什么您考虑在存在像Let's Encrypt这样出色的免费工具的情况下,通过不安全的连接请求用户凭据。
  • cookie_http_only保持为true,以便仅在HTTP上通过认证cookie进行读取,而不是通过客户端脚本。

要查看Minim的示例用法,请查看示例仓库

使用

按照以下方式加载您的Minim配置文件

$auth = new Authenticator(new Configuration('my-config-file.yml'));

从这里您可以登录用户

$auth->authenticate('email', 'password'); // Authenticate user, true on success false on failure.

或根据用户是否已登录来从页面重定向

// Check if user is authenticated.
if (!$auth->isAuthenticated()) {
    header('Location: /forbidden.php'); // Not logged in, go to jail.
    die();
}

限制

不要依赖Minim出厂时就是安全的,并且始终进行自己的渗透测试。