Download the PHP package laminas-api-tools/api-tools-mvc-auth without Composer

On this page you can find all versions of the php package laminas-api-tools/api-tools-mvc-auth. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package api-tools-mvc-auth

Laminas MVC Auth

Build Status

🇷🇺 Русским гражданам

Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.

У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.

Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"

🇺🇸 To Citizens of Russia

We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.

One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.

You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

Introduction

api-tools-mvc-auth is a Laminas module that adds services, events, and configuration that extends the base Laminas MVC lifecycle to handle authentication and authorization.

For authentication, 3 primary methods are supported out of the box: HTTP Basic authentication, HTTP Digest authentication, and OAuth2 (this requires Brent Shaffer's OAuth2 Server).

For authorization, this particular module delivers a pre-dispatch time listener that will identify if the given route match, along with the HTTP method, is authorized to be dispatched.

Requirements

Please see the composer.json file.

Installation

Run the following composer command:

Alternately, manually add the following to your composer.json, in the require section:

And then run composer update to ensure the module is installed.

Finally, add the module name to your project's config/application.config.php under the modules key:

Configuration

User Configuration

The top-level configuration key for user configuration of this module is api-tools-mvc-auth. Under this key, there are two sub-keys, one for authentication and the other for authorization.

Key: authentication

The authentication key is used for any configuration that is related to the process of authentication, or the process of validating an identity.

Sub-key: http

The http sub-key is utilized for configuring an HTTP-based authentication scheme. These schemes utilize Laminas's Laminas\Authentication\Adapter\Http adapter, which implements both HTTP Basic and HTTP Digest authentication. To accomplish this, the HTTP adapter uses a file based "resolver" in order to resolve the file containing credentials. These implementation nuances can be explored in the Authentication portion of the Laminas manual.

The http sub-key has several fields:

Beyond those configuration options, one or both of the following resolver configurations is required:

An example might look like the following:

Sub-key: map

The map subkey is used to map an API module (optionally, with a version namespace) to a given authentication type (typically, one of basic, digest, or oauth2). This can be used to enfore different authentication methods for different APIs, or even versions of the same API.

In the absence of a map subkey, if any authentication adapter configuration is defined, that configuration will be used for any API.

Note for users migrating from 1.0: In the 1.0 series, authentication was per-application, not per API. The migration to 1.1 should be seamless; if you do not edit your authentication settings, or provide authentication information to any APIs, your API will continue to act as it did. The first time you perform one of these actions, the Admin API will create a map, mapping each version of each service to the configured authentication scheme, and thus ensuring that your API continues to work as previously configured, while giving you the flexibility to define authentication per-API and per-version in the future.

Sub-key: types

Starting in 1.1.0, the concept of authentication adapters was provided. Adapters "provide" one or more authentication types; these are then used internally to determine which adapter to use, as well as by the Admin API to allow mapping APIs to specific authentication types.

In some instances you may be using listeners or other facilities for authenticating an API. In order to allow mapping these (which is primarily a documentation feature in such instances), the types subkey exists. This key is an array of string authentication types:

This key and its contents must be created manually.

Sub-key: adapters

Starting in 1.1.0, with the introduction of adapters, you can also configure named HTTP and OAuth2 adapters. The name provided will be used as the authentication type for purposes of mapping APIs to an authentication adapter.

The format for the adapters key is a key/value pair, with the key acting as the type, and the value as configuration for providing a Laminas\ApiTools\MvcAuth\Authentication\HttpAdapter or Laminas\ApiTools\MvcAuth\Authentication\OAuth2Adapter instance, as follows:

Key: authorization

Sub-Key: deny_by_default

deny_by_default toggles the default behavior for the Laminas\Permissions\Acl implementation. The default value is false, which means that if no authenticated user is present, and no permissions rule applies for the current resource, then access is allowed. Change this setting to true to require authenticated identities by default.

Example:

deny_by_default with api-tools-oauth2

When using deny_by_default => true with > api-tools-oauth2, you will need to explicitly allow POST on the OAuth2 controller in order for Authentication requests to be made.

As an example:

deny_by_default on apache2

If you deploy your project on Apache 2 and have enabled deny_by_default, you may observe "403 Forbidden" responses from your API. This is due to issue bshaffer/oauth2-server-php#503, an upstream library api-tools-mvc-auth depends upon. The solution is to add the following line to either your .htaccess file or Apache configuration:

If you deploy your project on nginx or your Apache 2 instance sits behind a reverse proxy, you will not be affected by this issue.

Sub-Key: Controller Service Name

Under the authorization key is an array of controller service name keyed authorization configuration settings. The structure of these arrays depends on the type of the controller service that you're attempting to grant or restrict access to.

For the typical Laminas based action controller, this array is keyed with actions. Under this key, each action name for the given controller service is associated with a permission array.

For api-tools-rest-based controllers, a top level key of either collection or entity is used. Under each of these keys will be an associated permission array.

A permission array consists of a keyed array of either default or an HTTP method. The values for each of these will be a boolean value where true means an authenticated user is required and where false means an authenticated user is not required. If an action or HTTP method is not idendified, the default value will be assumed. If there is no default, the behavior of the deny_by_default key (discussed above) will be assumed.

Below is an example:

System Configuration

The following configuration is provided in config/module.config.php to enable the module to function:

These services will be described in the events and services section.

Laminas Events

Events

Laminas\ApiTools\MvcAuth\MvcAuthEvent::EVENT_AUTHENTICATION (a.k.a "authentication")

This event is triggered in relation to MvcEvent::EVENT_ROUTE at 500 priority. It is registered via the Laminas\ApiTools\MvcAuth\MvcRouteListener event listener aggregate.

Laminas\ApiTools\MvcAuth\MvcAuthEvent::EVENT_AUTHENTICATION_POST (a.k.a "authentication.post")

This event is triggered in relation to MvcEvent::EVENT_ROUTE at 499 priority. It is registered via the Laminas\ApiTools\MvcAuth\MvcRouteListener event listener aggregate.

Laminas\ApiTools\MvcAuth\MvcAuthEvent::EVENT_AUTHORIZATION (a.k.a "authorization")

This event is triggered in relation to MvcEvent::EVENT_ROUTE at -600 priority. It is registered via the Laminas\ApiTools\MvcAuth\MvcRouteListener event listener aggregate.

Laminas\ApiTools\MvcAuth\MvcAuthEvent::EVENT_AUTHORIZATION_POST (a.k.a "authorization.post")

This event is triggered in relation to MvcEvent::EVENT_ROUTE at -601 priority. It is registered via the Laminas\ApiTools\MvcAuth\MvcRouteListener event listener aggregate.

Laminas\ApiTools\MvcAuth\MvcAuthEvent object

The MvcAuthEvent object provides contextual information when any authentication or authorization event is triggered. It persists the following:

Listeners

Laminas\ApiTools\MvcAuth\Authentication\DefaultAuthenticationListener

This listener is attached to the MvcAuth::EVENT_AUTHENTICATION event. It is primarily responsible for preforming any authentication and ensuring that an authenticated identity is persisted in both the MvcAuthEvent and MvcEvent objects (the latter under the event parameter Laminas\ApiTools\MvcAuth\Identity).

Laminas\ApiTools\MvcAuth\Authentication\DefaultAuthenticationPostListener

This listener is attached to the MvcAuth::EVENT_AUTHENTICATION_POST event. It is primarily responsible for determining if an unsuccessful authentication was preformed, and in that case it will attempt to set a 401 Unauthorized status on the MvcEvent's response object.

Laminas\ApiTools\MvcAuth\Authorization\DefaultAuthorizationListener

This listener is attached to the MvcAuth::EVENT_AUTHORIZATION event. It is primarily responsible for executing the isAuthorized() method on the configured authorization service.

Laminas\ApiTools\MvcAuth\Authorization\DefaultAuthorizationPostListener

This listener is attached to the MvcAuth::EVENT_AUTHORIZATION_POST event. It is primarily responsible for determining if the current request is authorized. In the case where the current request is not authorized, it will attempt to set a 403 Forbidden status on the MvcEvent's response object.

Laminas\ApiTools\MvcAuth\Authorization\DefaultResourceResolverListener

This listener is attached to the MvcAuth::EVENT_AUTHENTICATION_POST with a priority of -1. It is primarily responsible for creating and persisting a special name in the current event for api-tools-rest-based controllers when used in conjunction with api-tools-rest module.

Laminas Services

Controller Plugins

This module exposes the controller plugin getIdentity(), mapping to Laminas\ApiTools\MvcAuth\Identity\IdentityPlugin. This plugin will return the identity discovered during authentication as injected into the Laminas\Mvc\MvcEvent's Laminas\ApiTools\MvcAuth\Identity parameter. If no identity is present in the MvcEvent, or the identity present is not an instance of Laminas\ApiTools\MvcAuth\Identity\IdentityInterface, an instance of Laminas\ApiTools\MvcAuth\Identity\GuestIdentity will be returned.

Event Listener Services

The following services are provided and serve as event listeners:

Laminas\ApiTools\MvcAuth\Authentication (a.k.a "authentication")

This is an instance of Laminas\Authentication\AuthenticationService.

Laminas\ApiTools\MvcAuth\Authentication\AuthHttpAdapter

This is an instance of Laminas\Authentication\Adapter\Http.

Laminas\ApiTools\MvcAuth\Authorization\AclAuthorization (a.k.a "authorization", "Laminas\ApiTools\MvcAuth\Authorization\AuthorizationInterface")

This is an instance of Laminas\ApiTools\MvcAuth\Authorization\AclAuthorization, which in turn is an extension of Laminas\Permissions\Acl\Acl.

Laminas\ApiTools\MvcAuth\ApacheResolver

This is an instance of Laminas\Authentication\Adapter\Http\ApacheResolver. You can override the ApacheResolver with your own resolver by providing a custom factory.

Laminas\ApiTools\MvcAuth\FileResolver

This is an instance of Laminas\Authentication\Adapter\Http\FileResolver. You can override the FileResolver with your own resolver by providing a custom factory.

Authentication Adapters

Authentication adapters provide the most direct means for adding custom authentication facilities to your APIs. Adapters implement Laminas\ApiTools\MvcAuth\Authentication\AdapterInterface:

The provides() method should return an array of strings, each an authentication "type" that this adapter provides; as an example, the provided Laminas\ApiTools\MvcAuth\Authentication\HttpAdapter can provide basic and/or digest.

The matches($type) should test the given $type against what the adapter provides to determine if it can handle an authentication request. Typically, this can be done with return in_array($type, $this->provides(), true);

The getTypeFromRequest() method can be used to match an incoming request to the authentication type it resolves, if any. Examples might be deconstructing the Authorization header, or a custom header such as X-Api-Token.

The preAuth() method can be used to provide client challenges; typically, this will only ever be used by the included HttpAdapter.

Finally, the authenticate() method is used to attempt to authenticate an incoming request. I should return either a boolean false, indicating authentictaion failed, or an instance of Laminas\ApiTools\MvcAuth\Identity\IdentityInterface; if the latter is returned, that identity will be used for the duration of the request.

Adapters are attached to the DefaultAuthenticationListener. To attach your custom adapter, you will need to do one of the following:

Defining named HTTP and/or OAuth2 adapters

Since HTTP and OAuth2 support is built-in, api-tools-mvc-auth provides a configuration-driven approach for creating named adapters of these types. Each requires a unique key under the api-tools-mvc-auth.authentication.adapters configuration, and each type has its own format.

The above configuration would provide the authentication types ['api-basic', 'api-digest', 'user', 'client'] to your application, which can each them be associated in the authentication type map.

If you use api-tools-admin's Admin API and/or the Laminas API Tools UI to configure authentication adapters, the above configuration will be created for you.

Attaching an adapter during an event listener

The best event to attach to in this circumstances is the "authentication" event. When doing so, you'll want to attach at a priority > 1 to ensure it executes before the DefaultAuthenticationListener.

In the following example, we'll assume you've defined a service named MyCustomAuthenticationAdapter that returns an AdapterInterface implementation, and that the class is the Module class of your API or a module in your application.

By returning nothing, the DefaultAuthenticationListener will continue to execute, but will now also have the new adapter attached.

Using a delegator factory

Delegator Factories are a way to "decorate" an instance returned by the Laminas Framework ServiceManager in order to provide pre-conditions or alter the instance normally returned. In our case, we want to attach an adapter after the instance is created, but before it's returned.

In the following example, we'll assume you've defined a service named MyCustomAuthenticationAdapter that returns an AdapterInterface implementation. The following is a delegator factory for the DefaultAuthenticationListener that will inject our adapter.

We then need to tell the ServiceManager about the delegator factory; we do this in our module's config/module.config.php, or one of the config/autoload/ configuration files:

Once configured, our adapter will be attached to every instance of the DefaultAuthenticationListener that is retrieved.


All versions of api-tools-mvc-auth with dependencies

PHP Build Version
Package Version
Requires php Version ~8.0.0 || ~8.1.0 || ~8.2.0
laminas-api-tools/api-tools-api-problem Version ^1.5.0
laminas-api-tools/api-tools-content-negotiation Version ^1.8.0
laminas-api-tools/api-tools-oauth2 Version ^1.9
laminas/laminas-authentication Version ^2.5.3
laminas/laminas-eventmanager Version ^3.2
laminas/laminas-http Version ^2.5.4
laminas/laminas-mvc Version ^2.7.9 || ^3.0.2
laminas/laminas-permissions-acl Version ^2.6
laminas/laminas-permissions-rbac Version ^2.6.0 || ^3.0
laminas/laminas-servicemanager Version ^3.11
laminas/laminas-stdlib Version ^2.7.8 || ^3.0.1
laminas/laminas-zendframework-bridge Version ^1.1
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package laminas-api-tools/api-tools-mvc-auth contains the following files

Loading the files please wait ....