1. Go to this page and download the library: Download aeris/zf-auth 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/ */
aeris / zf-auth example snippets
return [
'modules' => [
'Aeris\ZfAuth',
// REQUIRED Dependencies
'Aeris\ZfDiConfig', // for fancy service manager config
// OPTIONAL Dependencies
'Zf\OAuth2', // if using OAuth IdentityProviders
'Zf\ContentNegotiation', // if using OAuth IdentityProviders
'DoctrineModule', // if using DoctrineOrmIdentityRepository
'DoctrineORMmodule', // if using DoctrineOrmIdentityRepository
'ZfcRbac', // if using Route Guards
]
];
// Note that unless you're customizing Zf\OAuth2 services,
// you probably will need all of the "optional" modules.
return [
// See https://github.com/zfcampus/zf-oauth2/blob/master/config/oauth2.local.php.dist
'zf-oauth2' => [...],
// See https://github.com/doctrine/DoctrineORMModule/blob/master/config/module.config.php
'doctrine' => [...],
// Aeris\ZfAuth configuration
'zf_auth' => [
'authentication' => [
// If you're using a Doctrine Entity as a user identity,
// supply the entity class here (
return [
'zend_rest' => [
'errors' => [
// ...
[
'error' => '\Aeris\ZfAuth\Exception\AuthenticationException',
'http_code' => 401,
'application_code' => 'authentication_error',
'details' => 'The request failed to be authenticated. Check your access keys, and try again.'
]
]
]
]
$identityProvider = $serviceLocator->get('Aeris\ZfAuth\IdentityProvider');
$user = $identityProvider->getIdentity();
// See "Authorization" docs for a more advanced approach to authorization.
if (in_array('admin', $user->getRoles()) {
$this->doLotsOfCoolThings();
}
else {
throw new UnauthorizedUserException();
}
use Aeris\ZfAuth\IdentityProvider\IdentityProviderInterface;
use Zend\Http\Request;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
class SuperSpecialIdentityProvider implements IdentityProviderInterface, ServiceLocatorAwareInterface {
use \Zend\ServiceManager\ServiceLocatorAwareTrait;
public function canAuthenticate() {
/** @var Request $request */
$request = $this->serviceLocator->get('Application')
->getMvcEvent()
->getRequest();
return $request->getQuery('super_secret_password') !== null;
}
/** @return \Aeris\ZfAuth\Identity\IdentityInterface */
public function getIdentity() {
/** @var Request $request */
$request = $this->serviceLocator->get('Application')
->getMvcEvent()
->getRequest();
$password = $request->getQuery('super_secret_password');
$isSuperSecretUser = $password === '42';
// Return null if we cannot authenticate the user
if ($isSuperSecretUser) {
return null;
}
// Return our super-secret user
return $this->serviceLocator
->get('entity_manager')
->getRepo('MyApp\Entity\User')
->findOneByUsername('superSecretUser');
}
}
// module.config.php
return [
'service_manager' => [
// Aeris\ZfDiConfig ftw
'di' => [
// Override default identity provider
'Aeris\ZfAuth\IdentityProvider' => [
// Wrap in ChainedIdentityProvider, so we still
// have access to other authenticators
'class' => 'Aeris\ZfAuth\IdentityProvider\ChainedIdentityProvider',
'setters' => [
'providers' => [
// Add our provider to the top of the list
'$factory:\MyApp\IdentityProviders\SuperSpecialIdentityProvider'
// Include default set of providers
'@Aeris\ZfAuth\IdentityProvider\OAuthUserIdentityProvider',
'@Aeris\ZfAuth\IdentityProvider\OAuthClientIdentityProvider',
'@Aeris\ZfAuth\IdentityProvider\AnonymousIdentityProvider'
]
]
]
]
]
];
namespace Aeris\ZfAuth\Guard;
use Zend\Mvc\Router\RouteMatch;
interface GuardInterface {
public function __construct(array $rules = []);
public function setRules(array $rules);
/** @return boolean */
public function isGranted(RouteMatch $event);
}
class UsernameGuard implements GuardInterface {
/** @var array */
protected $rules;
/** @var IdentityProviderInterface */
protected $identityProvider;
public function __construct(array $rules = []) {
$this->setRules($rules);
}
public function setRules(array $rules) {
$this->rules = $rules;
}
/** @return boolean */
public function isGranted(RouteMatch $routeMatch) {
$controller = $routeMatch->getParam('controller');
// Find usernames allowed for this controller
$allowedUsernames = array_reduce($this->rules, function($allowed, $rule) use ($controller) {
$isMatch = $rule['controller'] === $controller;
return array_merge($allowed, $isMatch ? $rule['usernames'] : []);
}, []);
$username = $this->identityProvider->getIdentity()->getUsername();
return in_array('*', $allowedUsernames) || in_array($username, $allowedUsernames);
}
public function setIdentityProvider(IdentityProviderInterface $identityProvider) {
$this->identityProvider = $identityProvider;
}
}
[
'guard_manager' => [
// Using Aeris\ZfDiConfig, because I'm fancy
// but you can use service factories if you want to be lame
'di' => [
'MyApp\Guard\UsernameGuard' => [
'class' => '\MyApp\Guard\UsernameGuard',
'setters' => [
'identityProvider' => '@Aeris\ZfAuth\IdentityProvider'
]
]
]
]
]
use Aeris\ZfAuth\Service\AuthServiceAwareInterface;
use Zend\Mvc\Controller\AbstractRestfulController;
class AnimalRestController extends AbstractRestfulController implements AuthServiceAwareInterface {
use \Aeris\ZfAuth\Service\AuthServiceAwareTrait;
public function create($data) {
$animal = new Animal($data);
// Check if the current identity is allowed to create this animal
if (!$this->authService->isGranted('create', $animal)) {
throw new AuthorizationException('Tsk tsk tsk, you cannot create an animal, you!');
}
$this->persist($animal);
return $animal;
}
}
class OnlyUsersCanCreateAnimalsVoter implements VoterInterface {
public function vote(TokenInterface $token, $resource, array $actions) {
// First, we need to decide whether we care about this resource/action
$doWeCare = $this->supportsClass(get_class($resource)) &&
Aeris\Fn\any($actions, [$this, 'supportsAttribute']);
if (!$doWeCare) {
// Returning ACCESS_ABSTAIN tells our AuthService to ignore
// the results of this voter
return self::ACCESS_ABSTAIN;
}
// We can get the current Identity from the $token argument
$currentIdentity = $token->getUser();
$isLoggedInUser = !($currentIdentity instanceof \Aeris\ZfAuth\Identity\AnonymousIdentity);
// Do not allow anonymous requests to create animals
return $isLoggedInUser ? self::ACCESS_GRANTED : self::ACCESS_DENIED;
}
public function supportsAttribute($action) {
// This voter only cares about `create` actions (aka "attributes")
return $action === 'create';
}
public function supportsClass($class) {
// This voter only cares about `Animal` objects
return $class === 'MyApp\Model\Animal' || is_a($class, 'MyApp\Model\Animal');
}
}
class OnlyMonkeysCanCreateMonkeysVoter implements VoterInterface {
public function vote(TokenInterface $token, $resource, array $actions) {
// Again, we need to decide whether we care about this resource/action
$doWeCare = $this->supportsClass(get_class($resource)) &&
Aeris\Fn\any($actions, [$this, 'supportsAttribute']) &&
// And in this case, we only care about animals which are also monkeys
$resource->getType() === 'monkey';
if (!$doWeCare) {
// Returning ACCESS_ABSTAIN tells our AuthService to ignore
// the results of this voter
return self::ACCESS_ABSTAIN;
}
// The $token is simply a Symfony interface which wraps a ZfAuth IdentityInterface object
$currentIdentity = $token->getUser();
$isCurrentIdentityAMonkey = $currentIdentity instanceof Animal && $currentIdentity->getType() === 'monkey';
return $isCurrentIdentityAMonkey ? self::ACCESS_GRANTED : self::ACCESS_DENIED;
}
public function supportsAttribute($action) {
// This voter only cares about `create` attribues (aka "actions")
return $action === 'create';
}
public function supportsClass($class) {
// This voter only cares about `Animal` objects
return $class === 'MyApp\Model\Animal' || is_a($class, 'MyApp\Model\Animal');
}
}
[
'zf_auth' => [
// Register voters here
'voter_manager' => [
// Accepts same config as `service_manager`
'di' => [
// Also accepts Aeris\ZfDiConfig
]
],
'voter_options' => [
// `strategy` can be one of:
// - 'affirmative': grant access as soon as any voter returns ACCESS_GRANTED
// - 'consensus': grant access if there are more voters granting access than there are denying
// - 'unanimous' (default): only grant access if none of the voters has denied access
'strategy' => 'unanimous',
'allow_if_all_abstain' => true,
]
]
]
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.