PHPackages                             erdiko/authorize - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. erdiko/authorize

AbandonedArchivedLibrary[Authentication &amp; Authorization](/categories/authentication)

erdiko/authorize
================

Authorize features

1.0.0(8y ago)51.1k41MITPHPPHP &gt;=5.4.0

Since Nov 29Pushed 8y ago5 watchersCompare

[ Source](https://github.com/Erdiko/authorize)[ Packagist](https://packagist.org/packages/erdiko/authorize)[ Docs](http://erdiko.org)[ RSS](/packages/erdiko-authorize/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (2)Versions (9)Used By (1)

Erdiko Authorize
================

[](#erdiko-authorize)

[![Package version](https://camo.githubusercontent.com/3d8a76e80e6e97f3b5270619ee875fa55e004fc9d9c509ba156d1eec931d00bd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f657264696b6f2f617574686f72697a652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/erdiko/authorize)[![CircleCI](https://camo.githubusercontent.com/fafcd879ee4ee0ed041d36c944f95f09196d265e29bc9dfefd03c13013f09fcd/68747470733a2f2f696d672e736869656c64732e696f2f636972636c6563692f70726f6a6563742f6769746875622f457264696b6f2f617574686f72697a652f646576656c6f702e7376673f7374796c653d666c61742d737175617265)](https://circleci.com/gh/Erdiko/authorize)[![license](https://camo.githubusercontent.com/b33dd49450d55401a9a9530b590cdd99aaa7f18c4ad487a5c20a550307b3eac1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f657264696b6f2f617574686f72697a652e7376673f7374796c653d666c61742d737175617265)](https://github.com/Erdiko/authorize/blob/master/LICENSE)

**Authorize**

An Erdiko package to provide user authorization.

Compatibility
-------------

[](#compatibility)

This package is compatible with PHP 5.4 or above and the latest version of Erdiko.

Installation
------------

[](#installation)

Add the eridko/authorize package using composer with this command:

`composer require erdiko/authorize`

##### Requirements

[](#requirements)

Between its requirements we count on Pimple and Symfony Security. In case of Pimple, we choose this package to manage Dependency Injection, allowing us to add more flexibility and extensibility. It also adds compatibility with Symfony Security module.

How to Use
----------

[](#how-to-use)

Once you have installed the package you are ready to start. Basic Role based Admin validation works out of the box!

To start using it in your code just create an instance of `Authorizer` class. This class will expect an instance of `AuthenticationManagerInterface` from symfony/security package as a constructor parameter.

Here's an example:

```
class AuthenticationManager implements AuthenticationManagerInterface
{
    private $authenticationManager;

    public function __construct()
    {
        // implements UserProviderInterface
        $userProvider = new InMemoryUserProvider(
            array(
                'bar@mail.com' => array(
                    'password' => 'asdf1234',
                    'roles'    => array('ROLE_ADMIN'),
                ),
                'foo@mail.com' => array(
                    'password' => 'asdf1234',
                    'roles'    => array('ROLE_USER'),
                ),
            )
        );

        // Create an encoder factory that will "encode" passwords
        $encoderFactory = new \Symfony\Component\Security\Core\Encoder\EncoderFactory(array(
            // We simply use plaintext passwords for users from this specific class
            'Symfony\Component\Security\Core\User\User' => new PlaintextPasswordEncoder(),
        ));

        // The user checker is a simple class that allows to check against different elements (user disabled, account expired etc)
        $userChecker = new UserChecker();
        // The (authentication) providers are a way to make sure to match credentials against users based on their "providerkey".
        $userProvider = array(
            new DaoAuthenticationProvider($userProvider, $userChecker, 'main', $encoderFactory, true),
        );

        $this->authenticationManager = new AuthenticationProviderManager($userProvider, true);
    }

    public function authenticate(TokenInterface $unauthenticatedToken)
    {

        try {
            $authenticatedToken = $this->authenticationManager->authenticate($unauthenticatedToken);
            Authorizer::startSession();
            $tokenStorage = new TokenStorage();
            $tokenStorage->setToken($authenticatedToken);
            $_SESSION['tokenstorage'] = $tokenStorage;
        } catch (\Exception $failed) {
            // authentication failed
            throw new \Exception($failed->getMessage());
        }
        return $authenticatedToken;
    }
}
```

It’s a best practice to add instance creation in the `_before` hook. An example of this best practice looks like this:

```
...
    public function _before()
    {
        $authManager = new AuthenticationManager();
        $this->auth = new Authorizer($authManager);
        // Run the parent beore filter to prep the theme
        parent::_before();
    }
...
```

You will then have a `$this->auth` attribute available to use in any *get* or *post* action. This will be used in `can`methods that determine access, allowing you to grant or reject access to a resource.

For example, if current user has ADMIN role, then it will be redirected to admin dashboard (GRANTED), otherwise the user will be redirected to login page (REJECTED).

```
   php public function getDashboard()
   {
       if($this->auth->can("VIEW_ADMIN_DASHBOARD")) {
           // Add page data
           $this->setTitle('Erdiko Admin Dashboard');
           $this->addView('examples/admin/dashboard');
       } else {
           \erdiko\core\helpers\FlashMessages::set("You SHALL NO Pass!!", "danger");
           $this->redirect('/users/login');
       }
   }

```

Note that in this example, current user is an instance of `Symfony\Component\Security\Core\Authentication\Token\TokenInterface`, stored in `$_SESSION['tokenstorage']`.

Also available is the “VIEW\_ADMIN\_DASHBOARD” attribute we will use to grant or reject access for the current user.

You can use the same logic to validate Models by adding a `__construct` method where you will place the authorize creation

```
   public function __construct()
   {
       $authManager = new AuthenticationManager();
       $this->auth = new Authorizer($authManager);
   }
```

Same for GRANT/REJECT:

```
   public function doSomething1()
   {
       if($this->auth->can("CAN_DO_1")) {
           return "success something one";
       } else {
           throw new \Exception("You are not granted");
       }
   }
```

Customization
-------------

[](#customization)

This package provides you with a framework to create custom validation. There are two different methods to create custom validation:

- Custom Voters

Implement `Symfony\Component\Security\Core\Authorization\Voter\VoterInterface`interface, and pass them in an array as second argument of `Authorizer` constructor.

- Custom Validator

Or you can create a `Validator` class that implements `erdiko\authorize ValidatorInterface` interface. Then you will have to register all validators in `/app/config/default/authorize.json`, and voila, all the custom validation logic you've created is already available to the authorizer.

authorize.json

```
{
     "validators":{
       "custom_types": [{
         "name": "example",
         "namespace": "app_validators_example",
         "classname": "ExampleValidator",
         "enabled": true
       }]
     }
   }
```

In these validator classes you will be able to define custom attributes, "VIEW\_ADMIN\_DASHBOARD" as we mention above, we might want to add "IS\_PREMIUM\_ACCOUNT", or any other attributes you want.

Note that `namespace` field of the above JSON indicate the class `namespace` and is related to the app root folder, e.g. `/app/validators/example/ExampleValidator.php`

Let's implement the example class registered in the example JSON.

```
class ExampleValidator implements ValidatorInterface
{
    public static function supportedAttributes()
    {
        return array('IS_PREMIUM_ACCOUNT');
    }

    public function supportsAttribute($attribute)
    {
        return in_array($attribute, self::supportedAttributes());
    }

    public function validate($token)
    {
        $result = false;
        $user = $token->getUser();
        if (!$user instanceof UserInterface) {
            $result = false;
        } else {
            $result = ($user->getRole()=='ROLE_PREMIUM');
        }
        return $result;
    }
}
```

Special Thanks
--------------

[](#special-thanks)

Arroyo Labs - For sponsoring development,

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 50% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~90 days

Total

3

Last Release

3228d ago

Major Versions

0.1.1 → 1.0.02017-07-12

### Community

Maintainers

![](https://www.gravatar.com/avatar/691c8888935e19e59a2dd12e4e056e9b05991f4ebe696ef27fc01db8e9d1c984?d=identicon)[arroyolabs](/maintainers/arroyolabs)

---

Top Contributors

[![ldaidone](https://avatars.githubusercontent.com/u/1054693?v=4)](https://github.com/ldaidone "ldaidone (27 commits)")[![arroyo](https://avatars.githubusercontent.com/u/378457?v=4)](https://github.com/arroyo "arroyo (19 commits)")[![pinedamg](https://avatars.githubusercontent.com/u/818713?v=4)](https://github.com/pinedamg "pinedamg (6 commits)")[![saarmstrong](https://avatars.githubusercontent.com/u/142324?v=4)](https://github.com/saarmstrong "saarmstrong (2 commits)")

---

Tags

authorizationauthorizererdikopimplesymfony-securityusersauthorizeerdikoerdiko-authorize

### Embed Badge

![Health badge](/badges/erdiko-authorize/health.svg)

```
[![Health](https://phpackages.com/badges/erdiko-authorize/health.svg)](https://phpackages.com/packages/erdiko-authorize)
```

###  Alternatives

[cnam/security-jwt-service-provider

Service Provider for usage jwt token for auth

60108.1k2](/packages/cnam-security-jwt-service-provider)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
