PHPackages                             zycon42/security - 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. zycon42/security

ActiveLibrary

zycon42/security
================

Security extension for Nette framework

v0.2-beta(11y ago)010MITPHPPHP &gt;= 5.4

Since Aug 15Pushed 11y ago1 watchersCompare

[ Source](https://github.com/Zycon42/Security)[ Packagist](https://packagist.org/packages/zycon42/security)[ RSS](/packages/zycon42-security/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (6)Versions (3)Used By (0)

Security
========

[](#security)

[![Build Status](https://camo.githubusercontent.com/83318c8908817a88f9ab855bd539b946c3ad3b3a9a966310326a25e77535d61f/68747470733a2f2f7472617669732d63692e6f72672f5a79636f6e34322f53656375726974792e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/Zycon42/Security)[![Latest release](https://camo.githubusercontent.com/e5126e9307e30f2f0eba26b51a80ae0e9109c7ccee00c6028e690d9177423b89/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7a79636f6e34322f73656375726974792e737667)](https://packagist.org/packages/zycon42/security)

Overview
--------

[](#overview)

Because I wasn't satisfied with current state of nette authorization mechanism I decided to port `Symfony/Security` into Nette.

It is largely based on `Symfony/Security-Core`. Sadly Nette authentication mechanism and `Nette\Security\User` class are incompatible with pure `Symfony/Security-Core`, so it was necessary to rewrite it.

Currently this project handles only Authorization for Authentication you have to use Nette classes. Also ACL isn't currently supported.

For more info how it works internally please refer to symfony security documentation.

Requirements
------------

[](#requirements)

This project requires php 5.4

- [Nette Framework](https://github.com/nette/nette)
- [Symfony Expression Language](https://github.com/symfony/expression-language)

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

[](#installation)

The best way to install Zycon42/Security is using the [Composer](http://getcomposer.org/):

```
$ composer require zycon42/security:~0.1
```

and then you have to enable it in your config.neon

```
extensions:
	security: Zycon42\Security\DI\SecurityExtension
```

Basic Usage
-----------

[](#basic-usage)

Main entry point for authorizations is `SecurityContext` class. Sample usage:

```
if (!$securityContext->isGranted('ROLE_ADMIN'))
    throw new ForbiddenRequestException('You need to be admin');
```

Code above will deny access if current user doesn't have role named `ADMIN`. Instead of roles you can use `IS_AUTHENTICATED` or `IS_ANONYMOUS` that grant access only to authenticated users or anonymous users respectively.

Also you can utilize optional secondary parameter `object` of `isGranted` method and ask if current user can perform given action on given resource like this:

```
if (!$securityContext->isGranted('EDIT', $post))
    throw new ForbiddenRequestException("You are not able to edit this $post");
```

Voters
------

[](#voters)

Symfony security uses idea of voters that vote if user will be granted or denied. Access decision manager collects these votes and decides based on them. Project ships with three voters. One for roles, second for `IS_AUTHENTICATED, IS_ANONYMOUS` tokens and last one for expressions which we will discuss later.

Using voters you can easily extend range of supported attributes and objects. You can for example implement typical use-case of user only allowed to edit own posts.

Create new voter implementing `Zycon42\Security\Authorization\Voters\IVoter` interface and then register it in DIC with specific tag

```
services:
    foo:
        class: YourVoter
        tags: [security.voter]
```

When you tag service with `security.voter` tag it will be added into `AccessDecisionManager` as voter.

For more information about voters and how to implement new one please refer to [symfony documentation](http://symfony.com/doc/current/cookbook/security/voters_data_permission.html) only remember that instead of `TokenInterface` we use `IIdentity` from nette.

Expressions
-----------

[](#expressions)

To be able to write more complex access rules you can use expressions. For parsing it we use `symfony/expression-language`.

There are several functions you can use in them:

- `isAnonymous()` returns true if current user isn't authenticated
- `isAuthenticated()` returns true if current user is authenticated
- `hasRole(string $role)` checks if user is in given role
- `hasPermission($object, $action)` checks if user has permission to perform action on object

Also you can access several variables:

- `identity` current user identity
- `user` nette user object `Nette\Security\User`
- `object` object that was passed as second parameter into `isGranted` method.
- `roles` array of identity roles

Example usage:

```
$securityContext->isGranted(new Expression("isAuthenticated() && !hasRole('CLIENT')"));
```

Presenter annotations
---------------------

[](#presenter-annotations)

To be able to use presenter annotations for granting/denying access use this in your secured presenter, which all your presenters that needs to use this, derive:

```
class SecuredPresenter extends BasePresenter
{
    // ... some code

    /**
     * @var PresenterRequirementsChecker
     * @inject
     */
    public $requirementsChecker;

    /**
     * {@inheritdoc}
     */
    public function checkRequirements($element) {
        if (!$this->requirementsChecker->checkRequirement($element, $this->request)) {
            // logged users get 403 and anonymous users get redirect to sign in
            if ($this->user->isLoggedIn()) {
                $expr = $this->requirementsChecker->getFailedExpression();
                throw new ForbiddenRequestException("Request didn't passed security expression \"$expr\"");
            } else {
                $this->redirect('Sign:in', ['backLink' => $this->storeRequest()]);
            }
        }
    }

    // ... some code
}
```

Remember not to override `checkRequirements` method in your derived presenters.

Now you can annotate your presenters and its `action/render/handle` methods with `@Security` annotations. Small example:

```
/**
 * @Security("hasRole('ADMIN')")
 */
class UsersPresenter extends SecuredPresenter
{
    // ... some code
}
```

or on `action` method

```
class UsersPresenter extends SecuredPresenter
{
    // ... some code

    /**
     * @Security("hasRole('ADMIN')")
     */
    public function actionEdit($id) {
        // ... implementation
    }
}
```

When using annotations on presenters note that annotations are inherited and are checked in order from base class to derived classes.

Expressions in annotations are same as these on `isGranted` but additionally you have access to all current request parameters as variables and object variable contains current request. So if you use something that converts presenter methods parameters from `id` to actual objects by adding additional request variables like `zycon42/param-converters` you will be able to write:

```
class PostPresenter extends SecuredPresenter
{
    // ... some code

        /**
         * @Security("hasPermission(post, 'EDIT')")
         */
        public function actionEdit(Post $post) {
            // ... implementation
        }
}
```

Configuration
-------------

[](#configuration)

Here you can find possible configuration options and its default values

```
security:
    decisionManager:
        strategy: affirmative
        allowIfAllAbstain: false
        allowIfEqualGrantedDenied: true
    voters:
        role: on
        authenticated: on
        expression: on
    roleHierarchy: false
```

In `roleHierarchy` section you can define how roles inherit from each other

```
security:
    roleHierarchy:
        ADMIN: { USER, MANAGER }
        MANAGER: { USER, CLIENT }
        CLIENT: GUEST
```

Note that ADMIN inheriting from USER is redundant because ADMIN inherits from USER through MANAGER. But here is list of each role effective list:

- ADMIN: ADMIN, USER, MANAGER, CLIENT, GUEST
- MANAGER: MANAGER, USER, CLIENT, GUEST
- CLIENT: CLIENT, GUEST

###  Health Score

21

—

LowBetter than 19% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~12 days

Total

2

Last Release

4272d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8eac2918a5adf98cc0b2a57d7cc4353b4671995d6af48cfc98f0a713ef0af753?d=identicon)[Zycon42](/maintainers/Zycon42)

---

Top Contributors

[![Zycon42](https://avatars.githubusercontent.com/u/1699787?v=4)](https://github.com/Zycon42 "Zycon42 (23 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/zycon42-security/health.svg)

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

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M647](/packages/sylius-sylius)[simplesamlphp/simplesamlphp

A PHP implementation of a SAML 2.0 service provider and identity provider.

1.1k12.4M192](/packages/simplesamlphp-simplesamlphp)[nette/nette

👪 Nette Framework - innovative framework for fast and easy development of secured web applications in PHP (metapackage)

1.6k2.8M333](/packages/nette-nette)[winzou/state-machine

A very lightweight yet powerful PHP state machine

52113.7M18](/packages/winzou-state-machine)[friendsofsymfony/http-cache-bundle

Set path based HTTP cache headers and send invalidation requests to your HTTP cache

43813.2M47](/packages/friendsofsymfony-http-cache-bundle)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)

PHPackages © 2026

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