xervice/security

3.0.0 2018-08-24 12:15 UTC

This package is auto-updated.

Last update: 2024-09-29 04:36:58 UTC


README

Scrutinizer Code Quality Code Coverage

为xervice实现安全服务。

安装

composer require xervice/security

配置

安全模块仅提供您自己的认证方法。您可以通过扩展SecurityDataProvider::getAuthenticatorList来定义它们。

<?php

namespace App\Security;

use Xervice\Security\SecurityDependencyProvider as XerviceSecurityDependencyProvider;

class SecurityDependencyProvider extends XerviceSecurityDependencyProvider
{
    /**
     * Give a list of valid authenticator (string => AuthenticatorInterface::class)
     * e.g.
     * token => tokenAuthenticator::class
     *
     * @return array
     */
    protected function getAuthenticatorList(): array
    {
        return [
            'myauth' => MyAuthenticator::class
        ];
    }

}

认证器

要定义自己的认证器,您必须实现接口 \Xervice\Security\Business\Authenticator\AuthenticatorInterface。

示例

<?php

namespace App\MyModule\Business\Authenticator;

use DataProvider\AuthenticatorDataProvider;
use DataProvider\SimpleCredentialsDataProvider;
use Xervice\Security\Business\Dependency\Authenticator\AuthenticatorInterface;
use Xervice\Security\Business\Exception\SecurityException;

class MyAuthenticator implements AuthenticatorInterface
{
    /**
     * @param \DataProvider\AuthenticatorDataProvider $dataProvider
     *
     * @throws \Xervice\Security\Business\Exception\SecurityException
     */
    public function authenticate(AuthenticatorDataProvider $dataProvider): void
    {
        if (!($dataProvider->getAuthData() instanceof SimpleCredentialsDataProvider)) {
            throw new SecurityException('Incorrect DataProvider for authenticator');
        }

        if (
            $dataProvider->getAuthData()->getUsername() !== 'staticusername'
            && $dataProvider->getAuthData()->getPassword() !== 'staticpassword'
        ) {
            throw new SecurityException('Authorization failed');
        }
    }
}

用法

要使用安全模块,您可以使用外观进行授权

$credentials = new SimpleCredentialsDataProvider();
$credentials
    ->setUsername('staticusername')
    ->setPassword('staticpassword');

$auth = new AuthenticatorDataProvider();
$auth->setAuthData($credentials);

$securityFacade = Locator::getInstance()->security()->facade()->authenticate(
    'myauthenticator',
    $auth
);