slimauth / slimauth
Slim Framework 3 身份验证中间件
0.1.0
2016-03-10 13:51 UTC
Requires
- php: >=5.5.0
Requires (Dev)
- phpunit/phpunit: ^4.8
- slim/slim: ~3.1
This package is auto-updated.
Last update: 2024-09-18 17:32:39 UTC
README
为 Slim Framework 提供的非官方身份验证中间件。
将身份验证和授权设置应用到每个路由上。
使用方法
中间件注册
<?php session_start(); $app = new \Slim\App([ 'auth' => function($c) { return new SlimAuth\Auth(function($id) { return User::findOne($id); // null => 403 response. }); } ]);
路由设置
使用 secure 方法。
<?php $auth = $app->getContainer()->get('auth'); $app->get('/private', function ($request, $response) { $response->getBody()->write('OK'); return $response; })->add($auth->secure());
会话身份验证
使用 permit 方法。
<?php $app->post('/login', function ($request, $response) { $parsedBody = $request->getParsedBody(); $user = User::findBy($parsedBody['user_cd']); if ($user && $user->authenticate($parsedBody['password'])) { $this->get('auth')->permit($user->id); } return $response->withRedirect('/', 301); });
处理会话身份验证
使用 clear 方法。
<?php $app->get('/logout', function ($request, $response) { $this->get('auth')->clear(); return $response->withRedirect('/', 301); });
高级使用
ACL 授权
使用 checkAcl 选项。
<?php $app = new \Slim\App([ 'auth' => function($c) { return new SlimAuth\Auth(function($id) { return User::findOne($id); }, [ 'checkAcl' => function($currentUser, $acl) { return $currentUser->allowAccess($acl); } ]); } ]);
使用带有 acl 列表的 secure 方法。
<?php $auth = $app->getContainer()->get('auth'); $app->get('/admin', function ($request, $response) { $response->getBody()->write('OK'); return $response; })->add($auth->secure(['admin', 'superuser']));
额外失败
使用 failure 选项。
<?php $app = new \Slim\App([ 'auth' => function($c) { return new SlimAuth\Auth(function($id) { return User::findOne($id); }, [ 'failure' => function($request, $response) { return $response->withRedirect('/', 301); } ]); } ]);
示例
使用以下命令启动示例。
$ php -S localhost:8080 -t example