symnedi / security
v0.3.0
2016-12-02 00:05 UTC
Requires
- php: ^7.0
- nette/di: ~2.4
- nette/http: ~2.4
- nette/security: ~2.4
- symfony/security-core: ~3.1
- symfony/security-http: ~3.1
- symnedi/event-dispatcher: ~0.2
Requires (Dev)
- nette/application: ~2.4
- nette/bootstrap: ~2.4
- nette/robot-loader: ~2.4
- nette/utils: ~2.4
- phpunit/phpunit: ~5.5
- symplify/coding-standard: ^1.2
- tracy/tracy: ~2.4
README
安装
composer require symnedi/security
注册扩展
# app/config/config.neon extensions: - Symnedi\Security\DI\SecurityExtension - Symnedi\EventDispatcher\DI\EventDispatcherExtension
用法
投票者
然后创建一个新的投票者实现 Symfony\Component\Security\Core\Authorization\Voter\VoterInterface
并将其注册为服务在 config.neon
services: - App\SomeModule\Security\Voter\MyVoter
然后在需要验证访问的地方,我们将使用 AuthorizationChecker
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; class Presenter { /** * @var AuthorizationCheckerInterface */ private $authorizationChecker; public function __construct(AuthorizationCheckerInterface $authorizationChecker) { $this->authorizationChecker = $authorizationChecker; } /** * @param PresenterComponentReflection $element */ public function checkRequirements($element) { if ($this->authorizationChecker->isGranted('access', $element) === FALSE) { throw new ForbiddenRequestException; } } }
防火墙
原始 Symfony 防火墙 简化了模块化支持。
我们需要创建的是一个 匹配器 和一个 监听器。
请求匹配器
此服务将匹配管理员模块中的所有站点 - 以 /admin
开头的 url
use Symfony\Component\HttpFoundation\Request; use Symnedi\Security\Contract\HttpFoundation\RequestMatcherInterface; class AdminRequestMatcher implements RequestMatcherInterface { /** * {@inheritdoc} */ public function getFirewallName() { return 'adminSecurity'; } /** * {@inheritdoc} */ public function matches(Request $request) { $url = $request->getPathInfo(); return strpos($url, '/admin') === 0; } }
防火墙监听器
它将确保用户已登录并且具有 'admin' 角色,否则将重定向。
use Nette\Application\AbortException; use Nette\Application\Application; use Nette\Application\Request; use Nette\Security\User; use Symnedi\Security\Contract\Http\FirewallListenerInterface; class LoggedAdminFirewallListener implements FirewallListenerInterface { /** * @var User */ private $user; public function __construct(User $user) { $this->user = $user; } /** * {@inheritdoc} */ public function getFirewallName() { return 'adminSecurity'; } /** * {@inheritdoc} */ public function handle(Application $application, Request $applicationRequest) { if ( ! $this->user->isLoggedIn()) { throw new AbortException; } if ( ! $this->user->isInRole('admin')) { throw new AbortException; } } }
然后我们注册这两个服务。
services: - AdminRequestMatcher - LoggedAdminFirewallListener
就这样!
测试
composer check-cs # see "scripts" section of composer.json for more details
vendor/bin/phpunit
贡献
规则很简单
- 新功能需要测试
- 所有测试必须通过
- 每个 PR 一个功能
我们很乐意合并你的功能!