PHP code example of xervice / security

1. Go to this page and download the library: Download xervice/security library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

xervice / security example snippets




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
        ];
    }

}



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
);