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

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

lucinda/security
================

API implementing common web security patterns (eg: authentication, authorization) for PHP applications based on OWASP guidelines

v4.1.4(3y ago)023.8k53MITPHPPHP ^8.1

Since Nov 7Pushed 1y ago1 watchersCompare

[ Source](https://github.com/aherne/php-security-api)[ Packagist](https://packagist.org/packages/lucinda/security)[ Docs](https://github.com/aherne/php-security-api)[ RSS](/packages/lucinda-security/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (48)Used By (3)

Web Security API
================

[](#web-security-api)

- [About](#about)
- [Configuration](#configuration)
- [Binding Points](#binding-points)
- [Execution](#execution)
- [Installation](#installation)
- [Unit Tests](#unit-tests)
- [Examples](#unit-tests)
- [Reference Guide](#reference-guide)

About
-----

[](#about)

This API is a **skeleton** (requires [binding](#binding-points) by developers) that implements common concerns of web security (authentication, authorization, state persistence, csrf prevention) based on OWASP guidelines, offering multiple binding points where developers MUST plugin components using its prototypes in order to complete the process (eg: DB authentication).

[![diagram](https://camo.githubusercontent.com/1ae852c2c779c64b46480dce50ef01cdea0971d2883dcec32c8b51030af72ecb/68747470733a2f2f7777772e6c7563696e64612d6672616d65776f726b2e636f6d2f7765622d73656375726974792d6170692e737667)](https://camo.githubusercontent.com/1ae852c2c779c64b46480dce50ef01cdea0971d2883dcec32c8b51030af72ecb/68747470733a2f2f7777772e6c7563696e64612d6672616d65776f726b2e636f6d2f7765622d73656375726974792d6170692e737667)

It does so using this series of steps:

- **[configuration](#configuration)**: setting up an XML file where web security is configured
- **[binding points](#binding-points)**: binding user-defined components defined in XML/code to API prototypes
- **[execution](#execution)**: creating a [Wrapper](https://github.com/aherne/php-security-api/blob/master/src/Wrapper.php) instance to authenticate &amp; authorize then use it to get logged in user id, access token (for stateless apps) or csrf token (for form logins)

API is fully PSR-4 compliant, only requiring PHP 8.1+ interpreter and SimpleXML + OpenSSL extensions. To quickly see how it works, check:

- **[installation](#installation)**: describes how to install API on your computer, in light of steps above
- **[unit tests](#unit-tests)**: API has 100% Unit Test coverage, using [UnitTest API](https://github.com/aherne/unit-testing) instead of PHPUnit for greater flexibility
- **[example](https://github.com/aherne/php-security-api/blob/master/tests/WrapperTest.php)**: shows a deep example of API functionality based on unit test for [Wrapper](https://github.com/aherne/php-security-api/blob/master/src/Wrapper.php)

All classes inside belong to **Lucinda\\WebSecurity** namespace!

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

[](#configuration)

To configure this API you must have a XML with following tags inside:

- **[security](#security)**: (mandatory) configures the api
- **[users](#users)**: (optional) required only if authentication is by XML (access control list)
- **[routes](#routes)**: (optional) required only if authorization is by XML (access control list)

### Security

[](#security)

Maximal syntax of this tag is:

```

```

Where:

- **security**: (mandatory) holds global web security policies.
    - **csrf**: (mandatory) holds settings necessary to produce an anti-CSRF token (useful to sign authentication with)
        - *secret*: (mandatory) password to use in encrypting csrf token (use: [Token\\SaltGenerator](https://github.com/aherne/php-security-api/blob/master/src/Token/SaltGenerator.php))
        - *expiration*: (optional) seconds until token expires. If not set, token will expire in 10 minutes.
    - **persistence** (mandatory) holds one or more mechanisms useful to preserve logged in state across requests (at least one is mandatory!)
        - **session**: (optional) configures persistence of logged in state by HTTP session
            - *parameter\_name*: (optional) name of $\_SESSION parameter that will store logged in state. If not set, "uid" is assumed.
            - *expiration*: (optional) seconds until session expires. If not set, session will expire as server-default.
            - *is\_http\_only*: (optional) whether or not to set session cookie as HttpOnly (can be 0 or 1; 0 is default).
            - *is\_https\_only*: (optional) whether or not to set session cookie as HTTPS only (can be 0 or 1; 0 is default).
            - *handler*: (optional) name of class (incl. namespace or relative path) implementing [SessionHandlerInterface](https://www.php.net/manual/en/class.sessionhandlerinterface.php) to which session handling will be delegated to.
        - **remember\_me**: (optional) configures persistence of logged in state by HTTP remember me cookie
            - *secret*: (mandatory) password to use in encrypting cookie (use: [Token\\SaltGenerator](https://github.com/aherne/php-security-api/blob/master/src/Token/SaltGenerator.php))
            - *parameter\_name*: (optional) name of $\_COOKIE parameter that will store logged in state. If not set, "uid" is assumed.
            - *expiration*: (optional) seconds until cookie expires. If not set, cookie will expire in one day.
            - *is\_http\_only*: (optional) whether or not to set cookie as HttpOnly (can be 0 or 1; 0 is default).
            - *is\_https\_only*: (optional) whether or not to set cookie as HTTPS only (can be 0 or 1; 0 is default).
        - **synchronizer\_token**: (optional) configures persistence of logged in state by signing every request with a synchronizer token
            - *secret*: (mandatory) password to use in encrypting token (use: [Token\\SaltGenerator](https://github.com/aherne/php-security-api/blob/master/src/Token/SaltGenerator.php))
            - *expiration*: (optional) seconds until token expires. If not set, token will expire in 1 hour.
            - *regeneration*: (optional) seconds from the moment token was created until it needs to regenerate on continuous usage. If not set, token will be regenerated in 1 minute.
        - **json\_web\_token**: (optional) configures persistence of logged in state by signing every request with a json web token
            - *secret*: (mandatory) password to use in encrypting token (use: [Token\\SaltGenerator](https://github.com/aherne/php-security-api/blob/master/src/Token/SaltGenerator.php))
            - *expiration*: (optional) seconds until token expires. If not set, token will expire in 1 hour.
            - *regeneration*: (optional) seconds from the moment token was created until it needs to regenerate on continuous usage. If not set, token will be regenerated in 1 minute.
    - **authentication**: (mandatory) holds one or more mechanisms to authenticate (at least one is mandatory!)
        - **form**: (optional) configures authentication via form. If no *dao* attribute is set, authentication is done via XML and [users](#users) tag is required!
            - *dao*: (optional) name of PSR-4 autoload-compliant class (incl. namespace) implementing [Authentication\\DAO\\UserAuthenticationDAO](#interface-userauthenticationdao) that performs form authentication in database. \[1\]
            - *throttler*: (optional) name of PSR-4 autoload-compliant class (incl. namespace) extending [Authentication\\Form\\LoginThrottler](#abstract-class-loginthrottler) that performs login throttling prevention
            - **login**: (optional) configures login
                - *page*: (optional) page that performs login operation (all requests to this page will pass through this filter), also one to redirect back if login is unsuccessful. If none, then "login" is implicitly used.
                - *target*: (optional) destination page after successful login. If none, then "index" is implicitly used.
                - *parameter\_username*: (optional) name of $\_POST parameter username will be submitted as. If none, then "username" is implicitly used.
                - *parameter\_password*: (optional) name of $\_POST parameter password will be submitted as. If none, then "password" is implicitly used.
                - *parameter\_rememberMe*: (optional) name of $\_POST parameter that activates "remember me" option (value can be 0 or 1). If none, then "remember\_me" is implicitly used.
            - **logout**: (optional) configures logout
                - *page*: (optional) page that performs logout operation (all requests to this page will pass through this filter). If none, then "logout" is implicitly used.
                - *target*: (optional) destination page after successful or unsuccessful logout. If none, then "login" is implicitly used.
        - **oauth2**: (optional) configures authentication via oauth2 provider
            - *dao*: (mandatory) name of PSR-4 autoload-compliant class (incl. namespace) implementing [Authentication\\OAuth2\\VendorAuthenticationDAO](#interface-oauth2-vendorauthenticationdao) that saves results of authentication in database
            - *target*: (optional) destination page after successful login. If none, then "index" is implicitly used.
            - *login*: (optional) generic page where login by provider option is available. If none, then "login" is implicitly used.
            - *logout*: (optional) page that performs logout operation. If none, then "logout" is implicitly used.
    - **authorization**: (mandatory) holds a single mechanism to authorize requests (at least one is mandatory!)
        - **by\_dao**: (optional) configures authorization by database
            - *page\_dao*: (mandatory) name of PSR-4 autoload-compliant class (incl. namespace) extending [Authorization\\DAO\\PageAuthorizationDAO](#abstract-class-pageauthorizationdao) that checks user rights in database
            - *user\_dao*: (mandatory) name of PSR-4 autoload-compliant class (incl. namespace) extending [Authorization\\DAO\\UserAuthorizationDAO](#abstract-class-UserAuthorizationDAO) that checks page rights in database
            - *logged\_in\_callback*: (optional) callback page for authenticated users when authorization fails. If none, then "index" is implicitly used.
            - *logged\_out\_callback*: (optional) callback page for guest users when authorization fails. If none, then "login" is implicitly used.
        - **by\_route**: (optional) configures authorization by XML, in which case [routes](#routes) tag is required. \[1\]
            - *logged\_in\_callback*: (optional) callback page for authenticated users when authorization fails. If none, then "index" is implicitly used.
            - *logged\_out\_callback*: (optional) callback page for guest users when authorization fails. If none, then "login" is implicitly used.

For examples of XMLs, check [WrapperTest](https://github.com/aherne/php-security-api/blob/master/tests/WrapperTest.php) @ unit tests!

Notes: (1) If authorization is **by\_route**, **authentication** is **form** with a *dao* attribute, then class referenced there must also implement [Authorization\\UserRoles](#interface-user-roles)!

### Users

[](#users)

This tag is required if XML authentication (**form** tag is present and has no *dao* attribute) + authorization (**by\_route** tag is present) are used. Syntax is:

```

    ...

```

Where:

- **users**: (mandatory) holds list of site users, each identified by a **user** tag
    - *roles*: (mandatory) holds list of roles guests (non-logged in users) belong to, separated by commas
    - **user**: (mandatory) holds information about a single user
        - *id*: (mandatory) holds unique user identifier (eg: 1)
        - *username*: (optional) holds user's username (eg: john\_doe). Mandatory for XML authentication!
        - *password*: (optional) holds user's password hashed using [password\_hash](https://www.php.net/manual/en/function.password-hash.php) (eg: value of `php password_hash("doe", PASSWORD_BCRYPT) `). Mandatory for XML authentication!
        - *roles*: (optional) holds list of roles user belongs to, separated by commas (eg: USERS, ADMINISTRATORS). Mandatory for XML authentication+authorization

If no user is detected in list above, GUEST role is automatically assumed!

### Routes

[](#routes)

This tag is required if XML authorization (**by\_route** tag is present) is used. Syntax is:

```

    ...

```

Where:

- **routes**: (mandatory) holds list of site routes, each identified by a **route** tag
    - *roles*: (mandatory) holds list of roles all pages are assumed to belong by default to, separated by commas (eg: GUEST)
    - **route**: (mandatory) holds policies about a specific route
        - *id*: (mandatory) page relative url (eg: administration)
        - *roles*: (mandatory) holds list of roles page is associated to, separated by commas (eg: USERS, ADMINISTRATORS)

Binding Points
--------------

[](#binding-points)

In order to remain flexible and achieve highest performance, API takes no more assumptions than those absolutely required! It offers developers instead an ability to bind to its prototypes in order to gain certain functionality.

### Declarative Binding

[](#declarative-binding)

It offers developers an ability to **bind declaratively** to its prototype classes/interfaces via XML:

XML Attribute @ TagClass PrototypeAbility Gained[dao @ form](#security)[Authentication\\DAO\\UserAuthenticationDAO](#interface-userauthenticationdao)Form authentication via database, always[throttler @ form](#security)[Authentication\\Form\\LoginThrottler](#abstract-class-loginthrottler)Form authentication protection against bruteforce attacks via database[dao @ oauth2](#security)[Authentication\\OAuth2\\VendorAuthenticationDAO](#interface-oauth2-vendorauthenticationdao)Authentication via oauth2 provider[page\_dao @ by\_dao](#security)[Authorization\\DAO\\PageAuthorizationDAO](#abstract-class-pageauthorizationdao)Authorization where ACL is checked in database[user\_dao @ by\_dao](#security)[Authorization\\DAO\\UserAuthorizationDAO](#abstract-class-UserAuthorizationDAO)Authorization where USER is checked in database[dao @ form](#security)[Authorization\\UserRoles](#interface-user-roles)Any authorization where user roles are checked in database### Programmatic Binding

[](#programmatic-binding)

It offers developers an ability to **bind programmatically** to its prototypes via [Wrapper](#execution) constructor:

Class PrototypeAbility Gained[Request](#class-request)(mandatory) Collects information about request to be authenticated/authorized.[Authentication\\OAuth2\\Driver](#interface-oauth2-driver)\[\](optional) Contains information about OAuth2 vendors to use in OAuth2 authentication later onExecution
---------

[](#execution)

Once [configuration](#configuration) is finished, one can finally use this API to authenticate and authorize by calling [Wrapper](https://github.com/aherne/php-security-api/blob/master/src/Wrapper.php), which defines following public methods:

MethodArgumentsReturnsDescription\_\_construct\\SimpleXMLElement $xml, [Request](https://github.com/aherne/php-security-api/blob/master/src/Request.php) $request, [Authentication\\OAuth2\\Driver](https://github.com/aherne/php-security-api/blob/master/src/Authentication/OAuth2/Driver.php)\[\] $oauth2Drivers = \[\]voidPerforms authentication and authorization of request based on argumentsgetUserIDvoidmixedGets logged in user id (integer or string)getCsrfTokenvoidstringGets anti-CSRF token to send as "csrf" POST parameter on form login and "state" GET parameter in oauth2 authorization code requestsgetAccessTokenvoidstringGets access token to sign stateless requests with as Bearer HTTP\_AUTHORIZATION header (applies if "synchronizer token" or "json web token" persistence is used)Both authentication and authorization require following objects to be set beforehand and constructor injected:

- [Request](#class-request): encapsulating request to be handled
- [Authentication\\OAuth2\\Driver](#interface-authentication-oauth2-driver)\[\]: encapsulating a list of OAuth2 vendors to authenticate with

If authentication/authorization reached a point where request needs to be redirected, constructor throws a [SecurityPacket](#class-securitypacket). It may also throw:

- [Authentication\\Form\\Exception](https://github.com/aherne/php-security-api/blob/master/src/Authentication/Form/Exception.php): when login form is posted with wrong parameters names
- [Authentication\\OAuth2\\Exception](https://github.com/aherne/php-security-api/blob/master/src/Authentication/OAuth2/Exception.php): when OAuth2 provider answers with an error to authorization code or access token requests
- [PersistenceDrivers\\Session\\HijackException](https://github.com/aherne/php-security-api/blob/master/src/PersistenceDrivers/Session/HijackException.php): when user id in session is associated to a different IP address
- [Token\\EncryptionException](https://github.com/aherne/php-security-api/blob/master/src/Token/EncryptionException.php): when token could not be decrypted
- [Token\\Exception](https://github.com/aherne/php-security-api/blob/master/src/Token/Exception.php): when CSRF token is invalid or missing as "csrf" POST param @ form login or "state" GET param @ oauth2 authorization code response
- [ConfigurationException](https://github.com/aherne/php-security-api/blob/master/src/ConfigurationException.php): when XML is misconfigured, referenced classes are not found or not fitting expected pattern

### Handling SecurityPacket

[](#handling-securitypacket)

Developers of non-stateless applications are supposed to handle this exception with something like:

```
try {
	// sets $xml and $request
	$object = new Lucinda\WebSecurity\Wrapper($xml, $request);
	// operate with $object to retrieve information
} catch (SecurityPacket $e) {
	header("Location: ".$e->getCallback()."?status=".$e->getStatus()."&penalty=".((integer) $e->getTimePenalty()));
	exit();
}
```

Developers of stateless web service applications, however, are supposed to handle this exception with something like:

```
try {
	// sets $xml and $request
	$object = new Lucinda\WebSecurity\Wrapper($xml, $request);
	// use $object to produce a response
} catch (SecurityPacket $e) {
	echo json_encode(["status"=>$e->getStatus(), "callback"=>$e->getCallback(), "penalty"=>(integer) $e->getTimePenalty(), "access_token"=>$e->getAccessToken()]);
	exit();
	// front end will handle above code and make a redirection
}
```

### Handling other exceptions

[](#handling-other-exceptions)

They can be handled as following:

```
use Lucinda\WebSecurity;

try {
	// sets $xml and $request
	$object = new Wrapper($xml, $request);
	// process $object
} catch (SecurityPacket $e) {
	// handle security packet as above
} catch (Authentication\Form\Exception $e) {
	// respond with a 400 Bad Request HTTP status (it's either foul play or misconfiguration)
} catch (PersistenceDrivers\Session\HijackException $e) {
	// respond with a 400 Bad Request HTTP status (it's always foul play)
} catch (Token\EncryptionException $e) {
	// respond with a 400 Bad Request HTTP status (it's always foul play)
} catch (Token\Exception $e) {
	// respond with a 400 Bad Request HTTP status (it's either foul play or misconfiguration)
} catch (ConfigurationException $e) {
	// show stack trace and exit (it's misconfiguration)
} catch (Authentication\OAuth2\Exception $e) {
	// handle as you want (error received from OAuth2 vendor usually from user's decision not to approve your access)
}
```

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

[](#installation)

First choose a folder, associate it to a domain then write this command in its folder using console:

```
composer require lucinda/security
```

Then create a *configuration.xml* file holding configuration settings (see [configuration](#configuration) above) and a *index.php* file (see [getting results](#getting-results) above) in project root with following code:

```
$request = new Lucinda\WebSecurity\Request();
$request->setIpAddress($_SERVER["REMOTE_ADDR"]);
$request->setUri($_SERVER["REQUEST_URI"]!="/"?substr($_SERVER["REQUEST_URI"],1):"index");
$request->setMethod($_SERVER["REQUEST_METHOD"]);
$request->setParameters($_POST);
$request->setAccessToken(isset($_SERVER["HTTP_AUTHORIZATION"]) && stripos($_SERVER["HTTP_AUTHORIZATION"], "Bearer ")===0?trim(substr($_SERVER["HTTP_AUTHORIZATION"], 7)):"");

try {
	// sets $xml and $request
	$object = new Lucinda\WebSecurity\Wrapper(simplexml_load_file("configuration.xml"), $request);
	// operate with $object to retrieve information
} catch (Lucinda\WebSecurity\SecurityPacket $e) {
	header("Location: ".$e->getCallback()."?status=".$e->getStatus()."&penalty=".((integer) $e->getTimePenalty()));
	exit();
}
```

Then make this file a bootstrap and start developing MVC pattern on top:

```
RewriteEngine on
RewriteRule ^(.*)$ index.php

```

Unit Tests
----------

[](#unit-tests)

For tests and examples, check following files/folders in API sources:

- [test.php](https://github.com/aherne/php-security-api/blob/master/test.php): runs unit tests in console
- [unit-tests.xml](https://github.com/aherne/php-security-api/blob/master/unit-tests.xml): sets up unit tests
- [tests](https://github.com/aherne/php-security-api/tree/v3.0.0/tests): unit tests for classes from [src](https://github.com/aherne/php-security-api/tree/v3.0.0/src) folder

Reference Guide
---------------

[](#reference-guide)

### Class SecurityPacket

[](#class-securitypacket)

[SecurityPacket](https://github.com/aherne/php-security-api/blob/master/src/SecurityPacket.php) class encapsulates an response to an authentication/authorization event that typically requires redirection and defines following methods relevant to developers:

MethodArgumentsReturnsDescriptiongetAccessTokenvoidstringGets access token to sign stateless requests with as Bearer HTTP\_AUTHORIZATION header (applies if "synchronizer token" or "json web token" persistence is used)getCallbackvoidinteger/stringGets URI inside application to redirect to in case of successful/insuccessful authentication or insuccessful authorizationgetStatusvoid[Authentication\\ResultStatus](https://github.com/aherne/php-security-api/blob/master/src/Authentication/ResultStatus.php) / [Authorization\\ResultStatus](https://github.com/aherne/php-security-api/blob/master/src/Authorization/ResultStatus.php)Gets authentication/authorization status (see below)getTimePenaltyvoidintegerSets number of seconds client will be banned from authenticating as anti-throttling measureValues of *getStatus* depend on argument enum case:

EnumCaseValueDescription[Authentication\\ResultStatus](https://github.com/aherne/php-security-api/blob/master/src/Authentication/ResultStatus.php)LOGIN\_FAILEDlogin\_oklogin was successful and a redirection to logged in homepage is required[Authentication\\ResultStatus](https://github.com/aherne/php-security-api/blob/master/src/Authentication/ResultStatus.php)LOGIN\_FAILEDlogin\_failedlogin failed and a redirection to login page is required[Authentication\\ResultStatus](https://github.com/aherne/php-security-api/blob/master/src/Authentication/ResultStatus.php)LOGOUT\_OKlogout\_oklogout was successful and a redirection to login page is required[Authentication\\ResultStatus](https://github.com/aherne/php-security-api/blob/master/src/Authentication/ResultStatus.php)LOGOUT\_FAILEDlogout\_failedlogout was unsuccessful and a redirection to login page is required[Authentication\\ResultStatus](https://github.com/aherne/php-security-api/blob/master/src/Authentication/ResultStatus.php)DEFERREDredirectredirection to OAuth2 vendor's authorization request page is required[Authorization\\ResultStatus](https://github.com/aherne/php-security-api/blob/master/src/Authorization/ResultStatus.php)NOT\_FOUNDnot\_foundroute requested by client not covered by any access policy[Authorization\\ResultStatus](https://github.com/aherne/php-security-api/blob/master/src/Authorization/ResultStatus.php)UNAUTHORIZEDunauthorizedroute requested by client requires authentication, thus redirection to login page is required[Authorization\\ResultStatus](https://github.com/aherne/php-security-api/blob/master/src/Authorization/ResultStatus.php)FORBIDDENforbiddenroute requested by client is forbidden to current logged in user, thus a redirection to logged in homepage is requiredUsage example:

### Class Request

[](#class-request)

[Request](https://github.com/aherne/php-security-api/blob/master/src/Request.php) encapsulates information about request necessary for authentication and authorization via following public methods:

MethodArgumentsReturnsDescriptionsetIpAddressstring $valuevoidSets ip address used by client (eg: value of $\_SERVER\["REMOTE\_ADDR"\])setContextPathstring $valuevoidSets context path that prefixes page requested by client (eg: prefix of $\_SERVER\["REQUEST\_URI"\])setUristring $valuevoidSets page/resource requested by client without trailing slash (eg: suffix of $\_SERVER\["REQUEST\_URI"\])setMethodstring $valuevoidSets HTTP method used by client in page request (eg: value of $\_SERVER\["REQUEST\_METHOD"\])setParametersarray $valuevoidSets parameters sent by client as GET/POST along with request (eg: value of $\_REQUEST)setAccessTokenstring $valuevoidSets access token detected from client headers for stateless login (eg: suffix of $\_SERVER\["HTTP\_AUTHORIZATION"\])getIpAddressstring $valuevoidGets ip address used by client (eg: value of $\_SERVER\["REMOTE\_ADDR"\])getContextPathstring $valuevoidGets context path that prefixes page requested by client (eg: prefix of $\_SERVER\["REQUEST\_URI"\])getUristring $valuevoidGets page/resource requested by client without trailing slash (eg: suffix of $\_SERVER\["REQUEST\_URI"\])getMethodstring $valuevoidGets HTTP method used by client in page request (eg: value of $\_SERVER\["REQUEST\_METHOD"\])getParametersarray $valuevoidGets parameters sent by client as GET/POST along with request (eg: value of $\_REQUEST)getAccessTokenstring $valuevoidGets access token detected from client headers for stateless login (eg: Bearer value of $\_SERVER\["HTTP\_AUTHORIZATION"\])Usage example:

### Interface OAuth2 Driver

[](#interface-oauth2-driver)

[Authentication\\OAuth2\\Driver](https://github.com/aherne/php-security-api/blob/master/src/Authentication/OAuth2/Driver.php) interface encapsulates an oauth2 vendor to authenticate with and defines following methods:

MethodArgumentsReturnsDescriptiongetAuthorizationCodestring $statestringGets URL to redirect to vendor in order for latter to send back an autorization codegetAccessTokenstring $authorizationCodestringAsks vendor to exchange authorization code with an access token and returns itgetUserInformationstring $accessToken[Authentication\\OAuth2\\UserInformation](#interface-oauth2-userinformation)Uses access token to get logged in user information from vendorgetCallbackUrlvoidstringGets login route of current OAuth2 provider (eg: login/facebook)getVendorNamevoidstringGets name of current OAuth2 provider (eg: facebook)Usage example:

### Interface OAuth2 UserInformation

[](#interface-oauth2-userinformation)

[Authentication\\OAuth2\\UserInformation](https://github.com/aherne/php-security-api/blob/master/src/Authentication/OAuth2/UserInformation.php) interface contains blueprints for retrieving information about logged in user on OAuth2 provider via following methods:

MethodArgumentsReturnsDescriptiongetEmailvoidstringGets remote user emailgetIdvoidinteger
stringGets remote user idgetNamevoidstringGets remote user nameUsage example:

### Interface OAuth2 VendorAuthenticationDAO

[](#interface-oauth2-vendorauthenticationdao)

[Authentication\\OAuth2\\VendorAuthenticationDAO](https://github.com/aherne/php-security-api/blob/master/src/Authentication/OAuth2/VendorAuthenticationDAO.php) interface contains blueprints for saving info about logged in user on OAuth2 provider via following methods:

MethodArgumentsReturnsDescriptionlogin[Authentication\\OAuth2\\UserInformation](#interface-oauth2-userinformation) $userInfo,
string $vendorName,
string $accessTokenstring|NULLLogs in OAuth2 user into current application. Exchanges authenticated OAuth2 user information for a local user ID.logoutmixed $userIDvoidLogs out local user and removes saved access tokenUsage example:

### Interface UserAuthenticationDAO

[](#interface-userauthenticationdao)

[Authentication\\DAO\\UserAuthenticationDAO](https://github.com/aherne/php-security-api/blob/master/src/Authentication/DAO/UserAuthenticationDAO.php) interface contains blueprints for form-based database authentication via following methods:

MethodArgumentsReturnsDescriptionloginstring $userName,
string $passwordmixedLogs in user in database, returning local user ID or NULL if none found.logoutmixed $userIDvoidLogs out local userUsage example:

### Abstract Class LoginThrottler

[](#abstract-class-loginthrottler)

[Authentication\\Form\\LoginThrottler](https://github.com/aherne/php-security-api/blob/master/src/Authentication/Form/LoginThrottler.php) abstract class encapsulates form login throttling algorithm (against brute-force attacks) on a datasource (sql or nosql) via following public methods:

MethodArgumentsReturnsDescription\_\_construct[Request](#class-request) $request,
string $userNamevoidSets request environment and user about to login, checking throttle status.getTimePenaltyvoidintGets time penalty (in seconds) to apply for found attackersetFailurevoidvoidSets current request as failed (attacker detected)setSuccessvoidvoidSets current request as normal (no attacker detected)Class must be extended in order to implement following abstract protected method:

MethodArgumentsReturnsDescriptionsetCurrentStatusvoidintDetects current throttling status based on user and request in a databaseUsage example:

### Abstract Class UserAuthorizationDAO

[](#abstract-class-userauthorizationdao)

[Authorization\\DAO\\UserAuthorizationDAO](https://github.com/aherne/php-security-api/blob/master/src/Authorization/DAO/UserAuthorizationDAO.php) abstract class encapsulates database authorization where user accounts are checked in database via following public methods:

MethodArgumentsReturnsDescription\_\_constructmixed $userIDvoidSets user id to authorizegetIDvoidmixedGets user id to authorizeClass must be extended in order to implement following abstract method:

MethodArgumentsReturnsDescriptionisAllowed[Authorization\\DAO\\PageAuthorizationDAO](#abstract-class-pageauthorizationdao) $dao,
string $httpMethodboolChecks if current user is allowed access to requested pageUsage example:

### Abstract Class PageAuthorizationDAO

[](#abstract-class-pageauthorizationdao)

[Authorization\\DAO\\PageAuthorizationDAO](https://github.com/aherne/php-security-api/blob/master/src/Authorization/DAO/PageAuthorizationDAO.php) abstract class encapsulates database authorization where access control list is checked in database via following public methods:

MethodArgumentsReturnsDescription\_\_constructstring $pageURLvoidSets requested page to check ACL forgetIDvoidint|NULLGets database ID of page requested or null if not foundClass must be extended in order to implement following abstract methods:

MethodArgumentsReturnsDescriptionisPublicvoidboolChecks in database if page is accessible by non-logged in usersdetectIDstring $pageURLint|NULLDetects and returns database ID of page requested and returns its valueUsage example:

### Interface UserRoles

[](#interface-userroles)

[Authorization\\UserRoles](https://github.com/aherne/php-security-api/blob/master/src/Authorization/UserRoles.php) interface defines blueprints for any authorization where user roles are checked in database via following public methods:

MethodArgumentsReturnsDescriptiongetRolesmixed $userIDarrayGets list of roles user belongs toUsage example:

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance29

Infrequent updates — may be unmaintained

Popularity26

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity85

Battle-tested with a long release history

 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 ~54 days

Recently: every ~214 days

Total

47

Last Release

587d ago

Major Versions

v1.0.x-dev → v2.0.02018-09-09

v2.1.1 → v3.0.02019-11-27

v2.1.2 → v3.0.1.52020-01-23

v3.2.1 → v4.0.02021-12-29

v3.2.2 → v4.0.12022-01-09

PHP version history (3 changes)v3.0.0PHP ^7.1

v4.0.0PHP ^8.1

v3.0.x-devPHP ^7.1|^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3382770?v=4)[Lucian Gabriel Popescu](/maintainers/aherne)[@aherne](https://github.com/aherne)

---

Top Contributors

[![aherne](https://avatars.githubusercontent.com/u/3382770?v=4)](https://github.com/aherne "aherne (101 commits)")

---

Tags

jwtxmlsecurityAuthenticationtokenoauth2authorizationowaspdao

### Embed Badge

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

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

###  Alternatives

[and/oauth

Simple and amazing OAuth library with many providers. Just try it out!

4645.2k2](/packages/and-oauth)

PHPackages © 2026

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