madesimple / slim-auth
Slim 框架的认证和授权中间件
v2.1.0
2022-12-08 13:57 UTC
Requires
- php: >=7.2
- psr/http-server-middleware: ^1.0
- psr/log: ^1
- slim/slim: ^4
Requires (Dev)
- firebase/php-jwt: ^5.0
- phpunit/phpunit: ^8
- psr/container: ^1.0
- slim/psr7: ^1.1
Suggests
- firebase/php-jwt: Required to use JwtAuthentication (^5.0)
This package is auto-updated.
Last update: 2024-09-08 17:32:30 UTC
README
用于 Slim 4 框架 的认证和授权中间件。
安装
composer require madesimple/slim-auth
认证
一个中间件,用于确定请求是否包含有效的认证令牌。该中间件设计得易于扩展,以
- 处理任何类型的令牌检索;
- 处理任何类型的验证方法;以及,
- 在认证成功时执行任何一系列操作。
要使用认证中间件到您的 Slim 应用程序,只需
use Slim\Middleware\Authentication\SimpleTokenAuthentication; /** @var \Slim\App $app The Slim application */ /** @var string $pattern Pattern for either the group or a route */ /** @var callable $callable A callable for a route */ // Add to all routes: $app->add(new SimpleTokenAuthentication($app->getContainer(), $options)); // Add to a group of routes: $app->group($pattern, function () {}) ->add(new SimpleTokenAuthentication($app->getContainer(), $options)); // Add to a specific route: $app->get($pattern, $callable) ->add(new SimpleTokenAuthentication($app->getContainer(), $options));
侧注:如果您打算将相同的认证添加到更多组/路由,我们建议将中间件放入 dependencies.php
。
认证的默认选项是
[ // boolean - whether to enforce an https connection 'secure' => true, // array - list of hostnames/IP addresses to ignore the secure flag 'relaxed' => ['localhost', '127.0.0.1'], // array - list of environment variables to check for the token (set to an empty array to skip) 'environment' => ['HTTP_AUTHORIZATION', 'REDIRECT_HTTP_AUTHORIZATION'], // string - the header to check for the token (set to false, null, or '' to skip) 'header' => 'X-Auth', // string - the regex to match the token ($match[$options['index']] is used as the token) 'regex' => '/(.*)/', // integer - the regex index to use as the token 'index' => 1, // string - the cookie to check for the token (set to false, null, or '' to skip) 'cookie' => 'X-Auth', // string - the identifier for the token in the payload 'payload' => null, // string - the name to store the token in the request attributes 'attribute' => 'token', // object - an instance of a Psr\LoggerInterface 'logger' => null, ];
当认证失败时,中间件抛出 HttpUnauthorizedException
异常。
SimpleTokenAuthentication
简单的令牌认证是认证的实现,允许用户提供一个可调用来验证令牌。该可调用通过选项传递给简单的令牌认证
[ // callable - function to validate the token [required] 'validate' => null, ];
可调用应具有以下签名
function ($token): bool { /** @var bool $isValid Populated by this function, true if the token is valid */ return $isValid; }
JwtAuthentication
JWT 认证是认证的实现,允许用户使用 JWT 作为认证令牌。JWT 认证覆盖了默认的正则表达式,并添加了两个额外的选项
[ // string - Overrides the default regex 'regex' => '/Bearer\s+(.*)$/i', // string - JWT secret [required] 'secret' => '', // array - list of JWT algorithms [optional] 'algorithm' => ['HS256', 'HS512', 'HS384'], ];
授权
一个中间件,用于确定已认证的请求是否有权限访问请求的路由。
当授权失败时,中间件抛出 HttpForbiddenException
异常。
注意:如果您需要在应用程序中间件内部访问路由,您需要将 Middleware\RoutingMiddleware
中间件添加到您的应用程序中,在调用 run()
之前。