PHPackages                             webiny/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. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. webiny/security

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

webiny/security
===============

Webiny Security Component

v1.6.1(8y ago)14811MITPHPPHP ^7

Since Sep 20Pushed 8y ago11 watchersCompare

[ Source](https://github.com/Webiny/Security)[ Packagist](https://packagist.org/packages/webiny/security)[ Docs](http://www.webiny.com/)[ RSS](/packages/webiny-security/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (1)Dependencies (8)Versions (23)Used By (1)

Security Component
==================

[](#security-component)

The security component is a layer that takes care of the authentication and authorization processes for you.

Install the component
---------------------

[](#install-the-component)

The best way to install the component is using Composer.

```
composer require webiny/security
```

For additional versions of the package, visit the [Packagist page](https://packagist.org/packages/webiny/security).

About
=====

[](#about)

Before we go into details, is important that you are familiar with the terms of authorization, authentication and access control, if you are not, please read the following articles:

-
-

If you what to know more:

-
-
- [http://en.wikipedia.org/wiki/Access\_control](http://en.wikipedia.org/wiki/Access_control)

Usage
=====

[](#usage)

NOTE: There are 2 ways of accessing your firewalls.

The long way:

```
$firewall = $this->security()->firewall('admin');
```

And the short way:

```
$firewall = $this->security('admin');
```

The usage of the component is fairly simple:

First you process the user login:

```
class MyClass
{
    use SecurityTrait;

    function loginUser()
    {
        $loginSuccessful = $this->security('admin')->processLogin();
    }
}
```

Then you can play around with the authorization methods:

```
class MyClass
{
    use SecurityTrait;

    function myMethod(){
        // get authenticated user
        $user = $this->security('admin')->getUser();

        // check if user has a role
        if($user->hasRole('ROLE_EDITOR')) {
            // user has role ROLE_EDITOR or any role with greater access level
        }

        // check if current user can access the current url
        if($this->security('admin')->isUserAllowedAccess()){
            // user can access the current url based on the defined access rules
        }
    }
}
```

If you wish to logout the user:

```
class MyClass
{
    use SecurityTrait;

    function logoutUser()
    {
        $logoutSuccessful = $this->security('admin')->processLogout();
    }
}
```

Example configuration
=====================

[](#example-configuration)

This is an example configuration. The next few topics will describe every part of the configuration.

```
Security:
    UserProviders:
        Memory:
            john: {password: secret, roles: 'ROLE_USER'}
            admin: {password: login123, roles: 'ROLE_SUPERADMIN'}
    AuthenticationProviders:
        OAuth2:
            Params:
                Server: FBAuth
                Roles: [ROLE_USER]
    Firewalls:
        Admin:
            RealmName: Administration
            Anonymous: true
            RememberMe: true
            TokenKey: SecretKey
            UserProviders: [Memory, OAuth2]
            AuthenticationProviders: [Http, Form, OAuth2]
```

Components
==========

[](#components)

The security layer is actually a set of several components that work and communicate together. The next few sections will go through the components and explain what they do.

Tokens (`Security.Tokens`)
--------------------------

[](#tokens-securitytokens)

Tokens are used to encrypt user data and save it into the session or cookie. Using tokens, once the user is authorized, we can do all future authorizations over the token, no need to use any authentication providers, check the database and things like that. Tokens save a lot of processing time.

Every token has two configuration parameters:

- `Driver`: name of a registered `Crypt` service
- `Params`: list of parameters that are being passed to the `Driver` constructor
- `SecurityKey`: key that will be used to encrypt token data; key must a length of 2n (8, 16, 32, 64 characters)

Example token definition:

```
Security:
    Tokens:
        SomeTokenName:
            Driver: '\Webiny\Component\Security\Token\CryptDrivers\Crypt\Crypt'
            SecurityKey: $3cR3tK3y # secret key that will be used to encrypt the token data
    Firewalls:
        Admin:
            Token: SomeTokenName
```

The built-in token driver is using the `Crypt` component, which is probably satisfying for the most cases. You can also have multiple tokens defined, with different drivers or security key, but you can only use one token per firewall.

By default, you don't need to define a `Token`, an internal token is automatically set for you. In case of the default token, you just need to define the `TokenKey` under your firewall:

```
Security:
    Firewalls:
        Admin:
            TokenKey: SecretKey
```

Encoders (`Security.Encoders`)
------------------------------

[](#encoders-securityencoders)

Encoders are services that are responsible for two things, creating a password hash from the provided string and verifying if the submitted password matches the given hash. Encoders do the similar thing like tokens, but tokens do encryption of user data, which can be decrypted, while encoders create hashes, which is not a reversible process, so you cannot get the original string.

The encoder component comes with a default `Crypt` driver, that uses the built in `Crypt` component, for hashing and verifying passwords.

The driver requires that you have `Crypt` service defined. Just provide the name of the service under `Params` and your encoder is ready.

Example encoder configuration:

```
# encoder configuration
Security:
    Encoders:
        EncoderOne:
            Driver: \Webiny\Component\Security\Encoder\Drivers\Crypt
        EncoderTwo:
            Driver: \Webiny\Component\Security\Encoder\Drivers\Plain
    Firewalls:
        Admin:
            Encoder: EncoderOne
```

To create a custom encoder driver, you need to create a class that implements `\Webiny\Component\Security\Encoder\EncoderDriverInterface`.

The component also comes with a `Plain` driver, which doesn't encode passwords, it keeps them in their plain format. You can also set `Encoder: false` under the `Firewall`. That will use the `Plain` driver.

By default you don't need to define an `Encoder`, an internal encoder is automatically defined for you.

User Providers (`Security.UserProviders`)
-----------------------------------------

[](#user-providers-securityuserproviders)

User providers are like a databases from where the `Security` component queries the users. Each provider consists of 2 parts, a user provider, and the user class itself. The provider part is responsible for loading users based on submitted login credentials, while the user object is responsible for verifying the submitted credentials against the loaded object from the provider.

There are four built-in user providers:

- `Memory`
- `OAuth2`
- `TwitterOAuth`
- `Entity`

### Memory provider

[](#memory-provider)

The `Memory` provider gives you the option to define users directly inside your configuration file, and it looks like this:

```
Security:
    UserProviders:
        MyTestMemoryUsers:
            john: {Password: secret, Roles: ROLE_USER}
            admin: {Password: login, Roles: [ROLE_SUPERADMIN, ROLE_GOD]}
        MyOtherMemoryUsers:
            marco: {password: polo, roles: ROLE_ADMIN}
    Firewall:
        Admin:
            UserProviders: [MyTestMemoryUsers, MyOtherMemoryUsers]
```

As you see, you can have multiple memory providers defined. Which one you wish to use, depends on how you define your firewall. You can use both of them, but we'll see more about that later.

**NOTE:**Make sure that you set `Encoder` to `false` on firewalls that are using `Memory` or some other provider that contains passwords in raw format, that is, where passwords are not encrypted. (NOTE: do not ever do that for production code).

### OAuth2 provider

[](#oauth2-provider)

The OAuth2 provider depends on the `OAuth2` component and it must be wrapped together with the authentication provider, described in the later topics. Basically, this provider gives you the option to do user authentication using any OAuth2 server, like Facebook, Google, LinkedIn, and many more.

To configure the OAuth2 user provider you just need to set the path to the built-in driver:

```
Security:
    UserProviders:
        SomeOAuth2Provider:
            Driver: '\Webiny\Component\Security\User\Providers\OAuth2\OAuth2Provider'
    Firewall:
        Admin:
            UserProviders: [SomeOAuth2Provider]
```

### TwitterOAuth provider

[](#twitteroauth-provider)

Unfortunately Twitter doesn't support the version 2 of OAuth protocol, just version 1, so we created a special TwitterOAuth provider. Its configuration is very similar to the OAuth2 user provider.

```
Security:
    UserProviders:
        MyTwitterOAuthProvider:
            Driver: '\Webiny\Component\Security\User\Providers\TwitterOAuth\TwitterOAuth'
    Firewall:
        UserProviders: [MyTwitterOAuthProvider]
```

### Entity provider

[](#entity-provider)

This provider uses the Entity component which is tied to your database.

```
Security:
    UserProviders:
        MyFromDatabaseProvider:
            Driver: '\Webiny\Component\Security\User\Providers\Entity\Entity'
            Params:
                Entity: 'My\App\Entities\User'
                Username: username
                Password: password
                Role: ROLE_USER
    Firewall:
        UserProviders: [MyFromDatabaseProvider]
```

**Entity** parameter points your entity class. **Username** defines the field name in the collection that holds the username. **Password** same as the username, just points to the password field. **Role** points either to the collection field holding the users role, or will be used as the role name, if the field doesn't exist.

### Custom user providers

[](#custom-user-providers)

To implement a custom user provider you need to create a class that implements `\Webiny\Component\Security\User\UserProviderInterface`. And you need to create a user class that extends `\Webiny\Component\Security\User\AbstractUser`. And that's it, all other details are described inside the interface and the abstract class.

### Combining multiple user providers

[](#combining-multiple-user-providers)

Each firewall can use one or more user providers. You can combine them how it best fits your needs. We will discuss that in the later topics.

### Authentication providers (`Security.AuthenticationProviders`)

[](#authentication-providers-securityauthenticationproviders)

Authentication providers are ways of authenticating users.

This is an example configuration for an authentication provider:

```
Security:
    AuthenticationProviders:
        Http:
            Driver: '\Webiny\Component\Security\Authentication\Providers\Http\Http'
        Facebook:
            Driver: '\Webiny\Component\Security\Authentication\Providers\OAuth2\OAuth2'
            Params:
                Server: Facebook # which OAuth2 server to use (defined under OAuth2 component)
                Roles: [ROLE_USER] # which role to assign to user authenticated with this provider
        TwitterOAuth:
            Driver: \Webiny\Component\Security\Authentication\Providers\TwitterOAuth\TwitterOAuth'
            Params:
                Server: ['MyTwitterApp'] # which twitter app to use (must be registered by TwitterOAuth component)
                Roles: [ROLE_USER] # which role to assign to user authenticated with this provider
    Firewall:
        Admin:
            AuthenticationProviders: [Http, Facebook, TwitterOAuth]
```

The configuration must have two parameters, the `Driver` param that defines which class to use to process the authentication, and an optional `Params` that forwards the different parameters to the driver constructor.

Additional parameters might be required for some other auth providers.

There are also four built-in auth providers:

#### Http auth provider

[](#http-auth-provider)

This is the basic Http authentication. Driver: `\Webiny\Component\Security\Authentication\Providers\Http\Http`

#### Form auth provider

[](#form-auth-provider)

Use this provider when you have a HTML login form for authenticating your users. Driver: `\Webiny\Component\Security\Authentication\Providers\Form\Form`.

Your HTML form must have these fields:

- `username`
- `password`
- `rememberme` (optional; default: "")

#### OAuth2 auth provider

[](#oauth2-auth-provider)

This provider uses the OAuth2 protocol and the `OAuth2` component. The supported OAuth2 servers are defined the by the `OAuth2` component. Driver: `\Webiny\Component\Security\Authentication\Providers\OAuth2\OAuth2`

This provider requires a bit more configuration, so here is an example:

```
Facebook:
    Driver: '\Webiny\Component\Security\Authentication\Providers\OAuth2\OAuth2'
    Params:
        Server: Facebook # which OAuth2 server to use (must be defined under OAuth2 component configuration)
        Roles: [ROLE_USER] # which role to assign to user authenticated with this provider
```

Notice the two attributes inside the params section, the `Server` attribute points to the defined OAuth2 configuration, while `Roles`param defines which roles will be assigned to users that are authenticated by this provider.

#### TwitterOAuth auth provider

[](#twitteroauth-auth-provider)

This auth provider is very similar to the OAuth2 auth provider, just this one is designed to work with Twitter OAuth server.

Here is an example configuration:

```
TwitterOAuth:
    Driver: \Webiny\Component\Security\Authentication\Providers\TwitterOAuth\TwitterOAuth'
    Params:
        Server: ['MyTwitterApp'] # which twitter app to use (must be registered by TwitterOAuth component)
        Roles: [ROLE_USER] # which role to assign to user authenticated with this provider
```

Firewall (`Security.Firewalls`)
-------------------------------

[](#firewall-securityfirewalls)

Firewall is the central component that controls the authentication layer.

You can have multiple sets of firewall. Each firewall consists of following parameters:

- `RealmName`
    - user readable name of the current firewall
- `Anonymous`
    - is anonymous access allowed behind this firewall or not
- `RememberMe`
    - do you want to remember the users credentials for a period of time or just the current session
    - if you wish to use the 'Remember me' feature on the page, this must be set to `true`
- `Encoder`
    - if your passwords are hashed (and they should be), place the name of your `Encoder` here
    - the encoder name must match the names under `Security.Encoders`
- `Token`
    - which token will the firewall use to encrypt user data
- `UserProviders`
    - these are the user providers that the firewall will use to ask for a user account
    - you can define an array of user providers, and the firewall will ask them one-by-one
- `AuthenticationProviders`
    - unlike user providers, that just return a user for the given username, authentication providers do the checking of user credentials
    - for example, authentication provider would ask the user to login over facebook, but the user provider, using facebook api, would retrieve the account
- `AccessControl`
    - set of urls and roles that are required to enter that area (you can find more information in the sections below)
- `RoleHierarchy`
    - defines the hierarchy of roles for the current firewall (you can find more information in the sections below)

### Access control

[](#access-control)

Access control is the central part that handles the authorization. Inside access control you define a set of rules, where each rule consist of a `Path` and a list of `Roles` that are required for accessing that path.

```
AccessControl:
    Rules:
        - {Path: '/^\/[a-zA-Z0-9-_]+\/[a-zA-Z0-9-_]+\/[a-zA-Z0-9]{13}$/', Roles: ROLE_ANONYMOUS}
        - {Path: '/^\/about/', Roles: [ROLE_USER,ROLE_EDITOR]}
        - {Path: '/^\/statistics/', Roles: ROLE_ANONYMOUS}
    DecisionStrategy: affirmative
```

If a rule is not matched, the built-in, `ROLE_ANONYMOUS`, will be returned as the required role to access that path.

### Voters

[](#voters)

Access control also has internal mechanism called `Voters`. These are like a jury that can either vote

- `ACCESS ALLOWED`
- `ACCESS_DENIED`
- `ACCESS_ABSTAINED`

There are two built-in voters, the `AuthenticationVoter` that votes based on if user is authenticated or not, and there is a `RoleVoter` that votes based on if user has the necessary role to access the current area.

The logic behind voters is created so you can extend it and add your own voters. For example you can create a voter that either allows or denies access based on users IP address, like a black-list filter.

To create a custom voter you need to create a class that implements `\Webiny\Component\Security\Authorization\Voters\VoterInterface`. After that, you need to create a service and tag it with `Security.Voter` tag.

```
MyComponent:
    Services:
        MyVoter:
            class: \MyCustomLib\MyCustomVoter
            tags: [Security.Voter]
```

### Decision strategy

[](#decision-strategy)

Decision strategy is the property that defines how the system will make its ruling, either to allow or deny access, based on the votes for the voters.

There are three different strategies that can be applied:

- *unanimous* - all voters must vote `ACCESS_ALLOWED` to allow access
- *affirmative* - only one `ACCESS_ALLOWED` vote is enough to allow access
- *consensus* - majority wins (tie denies access)

Role hierarchy (`Security.RoleHierarchy`)
-----------------------------------------

[](#role-hierarchy-securityrolehierarchy)

This component is mostly self-explanatory, it defines the list of available roles and their hierarchy.

Here is an example:

```
RoleHierarchy:
    ROLE_USER: ROLE_EDITOR
    ROLE_ADMIN: ROLE_USER
```

`ROLE_USER` will have access to all areas that require `ROLE_USER`, `ROLE_EDITOR` or `ROLE_ANONYMOUS`. `ROLE_ADMIN` will have access to all areas that require `ROLE_ADMIN`, `ROLE_USER`, `ROLE_EDITOR` or `ROLE_ANONYMOUS`.

Events
------

[](#events)

The component fires several events that you can subscribe to:

- `wf.security.login_invalid` fired when user submits invalid login credentials
- `wf.security.login_valid` fired when user submits valid login credentials
- `wf.security.role_invalid` fired when authenticated user tries to enter an area that requires a higher role than he currently has
- `wf.security.logout` fired when processLogout is called on a firewall
- `wf.security.not_authenticated` fired when a user tries to access an area for which he doesn't have a proper authorization level (role)

All these events pass an instance of `\Webiny\Component\Security\SecurityEvent`.

There are also some, user provider specific, events: `OAuth2` user provider event:

- `wf.security.user.oauth2` fired when user is authenticated over OAuth2 provider

`TwitterOAuth` user provider event:

- `wf.security.user.twitter` fired when user is authenticated over Twitter OAuth provider

Each of those two events, returns a different class, for OAuth2 it's `Webiny\Component\Security\User\Providers\OAuth2\OAuth2Event` and for Twitter it's `Webiny\Component\Security\User\Providers\TwitterOAuth`. Both classes have two methods, one returns an object, containing different user information we manged to get from the OAuth(2) server. The other method returns an instance of the OAuth class, either TwitterOAuth or OAuth2, giving you direct access to the API and the access key.

Using provider short codes
--------------------------

[](#using-provider-short-codes)

If you only need one instance of user or authentication provider, you can use short codes. With short codes you don't need to define the `Driver` parameter, and in cases of authentication provider, you don't need to define the auth provider under `Security.AuthenticationProviders`.

For example, this config can we written in a shorter version:

```
Security:
    UserProviders:
        OAuth2:
            Driver: '\Webiny\Component\Security\User\Providers\OAuth2\OAuth2Provider'
        TwitterOAuth:
            Driver: '\Webiny\Component\Security\User\Providers\TwitterOAuth\TwitterOAuth'
        Memory:
            john: {password: secret, roles: 'ROLE_USER'}
            admin: {password: login123, roles: 'ROLE_SUPERADMIN'}
        Entity:
            Driver: '\Webiny\Component\Security\User\Providers\Entity\Entity'
            Params:
                Entity: 'My\App\Entities\User'
                Username: username
                Password: password
                Role: ROLE_USER
    AuthenticationProviders:
        Http:
            Driver: '\Webiny\Component\Security\Authentication\Providers\Http\Http'
        Form:
            Driver: '\Webiny\Component\Security\Authentication\Providers\Form\Form'
        OAuth2:
            Driver: '\Webiny\Component\Security\Authentication\Providers\OAuth2\OAuth2'
            Params:
                Server: Facebook # which OAuth2 server to use (defined under OAuth2 component)
                Roles: [ROLE_USER] # which role to assign to user authenticated with this provider
        TwitterOAuth:
            Driver: \Webiny\Component\Security\Authentication\Providers\TwitterOAuth\TwitterOAuth'
            Params:
                Server: MyTwitterApp # which twitter app to use (must be registered by TwitterOAuth component)
                Roles: [ROLE_USER] # which role to assign to user authenticated with this provider
    Firewalls:
        Admin:
            RealmName: Administration
            Anonymous: true
            RememberMe: true
            UserProviders: [OAuth2, TwitterOAuth, Memory, Entity]
            AuthenticationProviders: [Http, Form, OAuth2, TwitterOAuth]
```

short version:

```
Security:
    UserProviders:
        Memory:
            john: {password: secret, roles: 'ROLE_USER'}
            admin: {password: login123, roles: 'ROLE_SUPERADMIN'}
        Entity:
            Params:
                Entity: 'My\App\Entities\User'
                Username: username
                Password: password
                Role: ROLE_USER
    AuthenticationProviders:
        OAuth2:
            Params:
                Server: Facebook # which OAuth2 server to use (defined under OAuth2 component)
                Roles: [ROLE_USER] # which role to assign to user authenticated with this provider
        TwitterOAuth:
            Params:
                Server: MyTwitterApp # which twitter app to use (must be registered by TwitterOAuth component)
                Roles: [ROLE_USER] # which role to assign to user authenticated with this provider
    Firewalls:
        Admin:
            RealmName: Administration
            Anonymous: true
            RememberMe: true
            UserProviders: [OAuth2, TwitterOAuth, Memory, Entity]
            AuthenticationProviders: [Http, Form, OAuth2, TwitterOAuth]
```

The key is that the name of the `UserProvider` or `AuthenticationProvider` matches the internal driver name. This is valid only for the internal providers, for custom provider you always need to define the `Driver`.

Resources
---------

[](#resources)

To run unit tests, you need to use the following command:

```
$ cd path/to/Webiny/Component/Security/
$ composer.phar install
$ phpunit

```

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 91.3% 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 ~52 days

Recently: every ~5 days

Total

22

Last Release

3153d ago

PHP version history (3 changes)1.0.x-devPHP &gt;=5.4.0

1.3.x-devPHP &gt;=5.5.9

1.5.x-devPHP ^7

### Community

Maintainers

![](https://www.gravatar.com/avatar/4440afa738ed146b05c06073a90345e0464c4f4d042b039532d881ca24859d77?d=identicon)[SvenAlHamad](/maintainers/SvenAlHamad)

---

Top Contributors

[![SvenAlHamad](https://avatars.githubusercontent.com/u/3808420?v=4)](https://github.com/SvenAlHamad "SvenAlHamad (21 commits)")[![adrians5j](https://avatars.githubusercontent.com/u/5121148?v=4)](https://github.com/adrians5j "adrians5j (2 commits)")

---

Tags

securityAuthenticationauthorizationacllogin

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[lusitanian/oauth

PHP 7.2 oAuth 1/2 Library

1.1k23.2M121](/packages/lusitanian-oauth)[efficiently/authority-controller

AuthorityController is an PHP authorization library for Laravel 5 which restricts what resources a given user is allowed to access.

15533.2k](/packages/efficiently-authority-controller)[hosseinhezami/laravel-permission-manager

Advanced permission manager for Laravel.

403.3k](/packages/hosseinhezami-laravel-permission-manager)

PHPackages © 2026

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