tuupola/slim-basic-auth
最新稳定版本:3.4.0
Composer 安装命令:
composer require tuupola/slim-basic-auth
包简介
PSR-7 and PSR-15 HTTP Basic Authentication Middleware
关键字:
README 文档
README
This middleware implements HTTP Basic Authentication. It was originally developed for Slim but can be used with all frameworks using PSR-7 or PSR-15 style middlewares. It has been tested with Slim Framework and Zend Expressive.
Heads up! You are reading documentation for 3.x branch which is PHP 7.1 and up only. If you are using older version of PHP see the 2.x branch. These two branches are not backwards compatible, see UPGRADING for instructions how to upgrade.
Install
Install latest version using composer.
$ composer require tuupola/slim-basic-auth
Usage
Configuration options are passed as an array. Only mandatory parameter is users. This is an array where you pass one or more "username" => "password" combinations. Username is the key and password is the value.
$app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "users" => [ "root" => "t00r", "somebody" => "passw0rd" ] ]));
Same with Zend Expressive.
$app = Zend\Expressive\AppFactory::create(); $app->pipe(new Tuupola\Middleware\HttpBasicAuthentication([ "users" => [ "root" => "t00r", "user" => "passw0rd" ] ]));
Rest of the examples assume you are using Slim Framework.
Cleartext passwords are only good for quick testing. You probably want to use hashed passwords. Hashed password can be generated with htpasswd command line tool or password_hash() PHP function
$ htpasswd -nbBC 10 root t00r
root:$2y$10$1lwCIlqktFZwEBIppL4ak.I1AHxjoKy9stLnbedwVMrt92aGz82.O
$ htpasswd -nbBC 10 somebody passw0rd
somebody:$2y$10$6/vGXuMUoRlJUeDN.bUWduge4GhQbgPkm6pfyGxwgEWT0vEkHKBUW
$app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "users" => [ "root" => '$2y$10$1lwCIlqktFZwEBIppL4ak.I1AHxjoKy9stLnbedwVMrt92aGz82.O', "somebody" => '$2y$10$6/vGXuMUoRlJUeDN.bUWduge4GhQbgPkm6pfyGxwgEWT0vEkHKBUW' ] ]));
Even if you are using hashed passwords it is not the best idea to store credentials in the code. Instead you could store them in environment or external file which is not committed to GitHub.
$app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "users" => [ "admin" => getenv("ADMIN_PASSWORD") ] ]));
Optional parameters
Path
The optional path parameter allows you to specify the protected part of your website. It can be either a string or an array. You do not need to specify each URL. Instead think of path setting as a folder. In the example below everything starting with /api will be authenticated.
$app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "path" => "/api", /* or ["/admin", "/api"] */ "realm" => "Protected", "users" => [ "root" => "t00r", "somebody" => "passw0rd" ] ]));
Ignore
With optional ignore parameter you can make exceptions to path parameter. In the example below everything starting with /api and /admin will be authenticated with the exception of /api/token and /admin/ping which will not be authenticated.
$app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "path" => ["/api", "/admin"], "ignore" => ["/api/token", "/admin/ping"], "realm" => "Protected", "users" => [ "root" => "t00r", "somebody" => "passw0rd" ] ]));
Before
Before function is called only when authentication succeeds but before the next incoming middleware is called. You can use this to alter the request before passing it to the next incoming middleware in the stack. If it returns anything else than \Psr\Http\Message\RequestInterface the return value will be ignored.
$app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "path" => "/admin", "realm" => "Protected", "users" => [ "root" => "t00r", "somebody" => "passw0rd" ], "before" => function ($request, $arguments) { return $request->withAttribute("user", $arguments["user"]); } ]));
After
After function is called only when authentication succeeds and after the incoming middleware stack has been called. You can use this to alter the response before passing it next outgoing middleware in the stack. If it returns anything else than \Psr\Http\Message\ResponseInterface the return value will be ignored.
$app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "path" => "/admin", "realm" => "Protected", "users" => [ "root" => "t00r", "somebody" => "passw0rd" ], "after" => function ($response, $arguments) { return $response->withHeader("X-Brawndo", "plants crave"); } ]));
Security
Basic authentication transmits credentials in clear text. For this reason HTTPS should always be used together with basic authentication. If the middleware detects insecure usage over HTTP it will throw a RuntimeException with the following message: Insecure use of middleware over HTTP denied by configuration.
By default, localhost is allowed to use HTTP. The security behavior of HttpBasicAuthentication can also be configured to allow:
- a whitelist of domains to connect insecurely
- forwarding of an HTTPS connection to HTTP
- all unencrypted traffic
How to configure a whitelist:
You can list hosts to allow access insecurely. For example, to allow HTTP traffic to your development host dev.example.com, add the hostname to the relaxed config key.
$app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "path" => "/admin", "secure" => true, "relaxed" => ["localhost", "dev.example.com"], "users" => [ "root" => "t00r", "somebody" => "passw0rd" ] ]));
Allow HTTPS termination and forwarding
If public traffic terminates SSL on a load balancer or proxy and forwards to the application host insecurely, HttpBasicAuthentication can inspect request headers to ensure that the original client request was initiated securely. To enable, add the string headers to the relaxed config key.
$app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "path" => "/admin", "secure" => true, "relaxed" => ["localhost", "headers"], "users" => [ "root" => "t00r", "somebody" => "passw0rd" ] ]));
Allow all unencrypted traffic
To allow insecure usage by any host, you must enable it manually by setting secure to false. This is generally a bad idea. Use only if you know what you are doing.
$app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "path" => "/admin", "secure" => false, "users" => [ "root" => "t00r", "somebody" => "passw0rd" ] ]));
Custom authentication methods
Sometimes passing users in an array is not enough. To authenticate against custom datasource you can pass a callable as authenticator parameter. This can be either a class which implements AuthenticatorInterface or anonymous function. Callable receives an array containing user and password as argument. In both cases authenticator must return either true or false.
If you are creating an Enterprise™ software which randomly lets people log in you could use the following.
use Tuupola\Middleware\HttpBasicAuthentication\AuthenticatorInterface; use Tuupola\Middleware\HttpBasicAuthentication; class RandomAuthenticator implements AuthenticatorInterface { public function __invoke(array $arguments): bool { return (bool)rand(0,1); } } $app = new Slim\App; $app->add(new HttpBasicAuthentication([ "path" => "/admin", "realm" => "Protected", "authenticator" => new RandomAuthenticator ]));
Same thing can also be accomplished with anonymous function.
$app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "path" => "/admin", "realm" => "Protected", "authenticator" => function ($arguments) { return (bool)rand(0,1); } ]));
Setting response body when authentication fails
By default plugin returns an empty response body with 401 response. You can return custom body using by providing an error handler. This is useful for example when you need additional information why authentication failed.
$app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "path" => "/api", "realm" => "Protected", "users" => [ "root" => "t00r", "somebody" => "passw0rd" ], "error" => function ($response, $arguments) { $data = []; $data["status"] = "error"; $data["message"] = $arguments["message"]; $body = $response->getBody(); $body->write(json_encode($data, JSON_UNESCAPED_SLASHES)); return $response->withBody($body); } ]));
Usage with PDO
For those in hurry there is a ready made PDO authenticator. It covers most of the use cases. You probably end up implementing your own though.
use Tuupola\Middleware\HttpBasicAuthentication\PdoAuthenticator; $pdo = new PDO("sqlite:/tmp/users.sqlite"); $app = new Slim\App; $app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "path" => "/admin", "realm" => "Protected", "authenticator" => new PdoAuthenticator([ "pdo" => $pdo ]) ]));
For better explanation see Basic Authentication from Database blog post.
Usage with FastCGI
By default Apache does not pass credentials to FastCGI process. If you are using mod_fcgi you can configure authorization headers with:
FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization
Testing
You can run tests either manually or automatically on every code change. Automatic tests require entr to work.
$ make test
$ brew install entr $ make watch
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email tuupola@appelsiini.net instead of using the issue tracker.
License
The MIT License (MIT). Please see LICENSE for more information.
tuupola/slim-basic-auth 适用场景与选型建议
tuupola/slim-basic-auth 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.9M 次下载、GitHub Stars 达 443, 最近一次更新时间为 2026 年 01 月 04 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「middleware」 「auth」 「psr-7」 「psr-15」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 tuupola/slim-basic-auth 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 tuupola/slim-basic-auth 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 tuupola/slim-basic-auth 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Shoot aims to make providing data to your templates more manageable
Laravel Multiauth package
Model of a web-based resource
A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.
Interfaces for web resource models and services to retrieve and create them
Interface for a factory to create Psr\Http\Message\StreamInterface objects
统计信息
- 总下载量: 1.9M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 458
- 点击次数: 29
- 依赖项目数: 32
- 推荐数: 2
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-04