PHP code example of laminas-api-tools / api-tools-mvc-auth

1. Go to this page and download the library: Download laminas-api-tools/api-tools-mvc-auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

laminas-api-tools / api-tools-mvc-auth example snippets


return [
    /* ... */
    'modules' => [
        /* ... */
        'Laminas\ApiTools\MvcAuth',
    ],
    /* ... */
];

'http' => [
    'accept_schemes' => ['basic', 'digest'],
    'realm' => 'My Web Site',
    'digest_domains' => '/',
    'nonce_timeout' => 3600,
    'htpasswd' => APPLICATION_PATH . '/data/htpasswd', // htpasswd tool generated
    'htdigest' => APPLICATION_PATH . '/data/htdigest', // @see http://www.askapache.com/online-tools/htpasswd-generator/
],

return [
    'api-tools-mvc-auth' => [
        'authentication' => [
            'map' => [
                'Status\V1' => 'basic',  // v1 only!
                'Status\V2' => 'oauth2', // v2 only!
                'Ping'      => 'digest', // all versions!
            ],
        ],
    ],
];

return [
    'api-tools-mvc-auth' => [
        'authentication' => [
            'types' => [
                'token',
                'key',
            ],
        ],
    ],
];

return [
    'api-tools-mvc-auth' => [
        'authentication' => [
            'adapters' => [
                'api' => [
                    // This defines an HTTP adapter that can satisfy both
                    // basic and digest.
                    'adapter' => 'Laminas\ApiTools\MvcAuth\Authentication\HttpAdapter',
                    'options' => [
                        'accept_schemes' => ['basic', 'digest'],
                        'realm' => 'api',
                        'digest_domains' => 'https://example.com',
                        'nonce_timeout' => 3600,
                        'htpasswd' => 'data/htpasswd',
                        'htdigest' => 'data/htdigest',
                    ],
                ],
                'user' => [
                    // This defines an OAuth2 adapter backed by PDO.
                    'adapter' => 'Laminas\ApiTools\MvcAuth\Authentication\OAuth2Adapter',
                    'storage' => [
                        'adapter' => 'pdo',
                        'dsn' => 'mysql:host=localhost;dbname=oauth2',
                        'username' => 'username',
                        'password' => 'password',
                        'options' => [
                            1002 => 'SET NAMES utf8', // PDO::MYSQL_ATTR_INIT_COMMAND
                        ],
                    ],
                ],
                'client' => [
                    // This defines an OAuth2 adapter backed by Mongo.
                    'adapter' => 'Laminas\ApiTools\MvcAuth\Authentication\OAuth2Adapter',
                    'storage' => [
                        'adapter' => 'mongo',
                        'locator_name' => 'SomeServiceName', // If provided, pulls the given service
                        'dsn' => 'mongodb://localhost',
                        'database' => 'oauth2',
                        'options' => [
                            'username' => 'username',
                            'password' => 'password',
                            'connectTimeoutMS' => 500,
                        ],
                    ],
                ],
            ],
        ],
    ],
];

'deny_by_default' => false,

> 'authorization' => [
>     'deny_by_default' => true,
>     'Laminas\\ApiTools\\OAuth2\\Controller\\Auth' => [
>         'actions' => [
>             'token' => [
>                 'GET'    => false,
>                 'POST'   => true,   // <-----
>                 'PATCH'  => false,
>                 'PUT'    => false,
>                 'DELETE' => false,
>             ],
>         ],
>     ],
> ],
> 

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

'authorization' => [
    'Controller\Service\Name' => [
        'actions' => [
            'action' => [
                'default' => boolean,
                'GET' => boolean,
                'POST' => boolean,
                // etc.
            ],
        ],
        'collection' => [
            'default' => boolean,
            'GET' => boolean,
            'POST' => boolean,
            // etc.
        ],
        'entity' => [
            'default' => boolean,
            'GET' => boolean,
            'POST' => boolean,
            // etc.
        ],
    ],
],

'service_manager' => [
    'aliases' => [
        'authentication' => 'Laminas\ApiTools\MvcAuth\Authentication',
        'authorization' => 'Laminas\ApiTools\MvcAuth\Authorization\AuthorizationInterface',
        'Laminas\ApiTools\MvcAuth\Authorization\AuthorizationInterface' => 'Laminas\ApiTools\MvcAuth\Authorization\AclAuthorization',
    ],
    'factories' => [
        'Laminas\ApiTools\MvcAuth\Authentication' => 'Laminas\ApiTools\MvcAuth\Factory\AuthenticationServiceFactory',
        'Laminas\ApiTools\MvcAuth\ApacheResolver' => 'Laminas\ApiTools\MvcAuth\Factory\ApacheResolverFactory',
        'Laminas\ApiTools\MvcAuth\FileResolver' => 'Laminas\ApiTools\MvcAuth\Factory\FileResolverFactory',
        'Laminas\ApiTools\MvcAuth\Authentication\DefaultAuthenticationListener' => 'Laminas\ApiTools\MvcAuth\Factory\DefaultAuthenticationListenerFactory',
        'Laminas\ApiTools\MvcAuth\Authentication\AuthHttpAdapter' => 'Laminas\ApiTools\MvcAuth\Factory\DefaultAuthHttpAdapterFactory',
        'Laminas\ApiTools\MvcAuth\Authorization\AclAuthorization' => 'Laminas\ApiTools\MvcAuth\Factory\AclAuthorizationFactory',
        'Laminas\ApiTools\MvcAuth\Authorization\DefaultAuthorizationListener' => 'Laminas\ApiTools\MvcAuth\Factory\DefaultAuthorizationListenerFactory',
        'Laminas\ApiTools\MvcAuth\Authorization\DefaultResourceResolverListener' => 'Laminas\ApiTools\MvcAuth\Factory\DefaultResourceResolverListenerFactory',
    ],
    'invokables' => [
        'Laminas\ApiTools\MvcAuth\Authentication\DefaultAuthenticationPostListener' => 'Laminas\ApiTools\MvcAuth\Authentication\DefaultAuthenticationPostListener',
        'Laminas\ApiTools\MvcAuth\Authorization\DefaultAuthorizationPostListener' => 'Laminas\ApiTools\MvcAuth\Authorization\DefaultAuthorizationPostListener',
    ],
],

namespace Laminas\ApiTools\MvcAuth\Authentication;

use Laminas\Http\Request;
use Laminas\Http\Response;
use Laminas\ApiTools\MvcAuth\Identity\IdentityInterface;
use Laminas\ApiTools\MvcAuth\MvcAuthEvent;

interface AdapterInterface
{
    /**
     * @return array Array of types this adapter can handle.
     */
    public function provides();

    /**
     * Attempt to match a requested authentication type
     * against what the adapter provides.
     *
     * @param string $type
     * @return bool
     */
    public function matches($type);

    /**
     * Attempt to retrieve the authentication type based on the request.
     *
     * Allows an adapter to have custom logic for detecting if a request
     * might be providing credentials it's interested in.
     *
     * @param Request $request
     * @return false|string
     */
    public function getTypeFromRequest(Request $request);

    /**
     * Perform pre-flight authentication operations.
     *
     * Use case would be for providing authentication challenge headers.
     *
     * @param Request $request
     * @param Response $response
     * @return void|Response
     */
    public function preAuth(Request $request, Response $response);

    /**
     * Attempt to authenticate the current request.
     *
     * @param Request $request
     * @param Response $response
     * @param MvcAuthEvent $mvcAuthEvent
     * @return false|IdentityInterface False on failure, IdentityInterface
     *     otherwise
     */
    public function authenticate(Request $request, Response $response, MvcAuthEvent $mvcAuthEvent);
}

return [
    /* ... */
    'api-tools-mvc-auth' => [
        'authentication' => [
            'adapters' => [
                'api' => [
                    // This defines an HTTP adapter that can satisfy both
                    // basic and digest.
                    'adapter' => 'Laminas\ApiTools\MvcAuth\Authentication\HttpAdapter',
                    'options' => [
                        'accept_schemes' => ['basic', 'digest'],
                        'realm' => 'api',
                        'digest_domains' => 'https://example.com',
                        'nonce_timeout' => 3600,
                        'htpasswd' => 'data/htpasswd',
                        'htdigest' => 'data/htdigest',
                    ],
                ],
                'user' => [
                    // This defines an OAuth2 adapter backed by PDO.
                    'adapter' => 'Laminas\ApiTools\MvcAuth\Authentication\OAuth2Adapter',
                    'storage' => [
                        'adapter' => 'pdo',
                        'dsn' => 'mysql:host=localhost;dbname=oauth2',
                        'username' => 'username',
                        'password' => 'password',
                        'options' => [
                            1002 => 'SET NAMES utf8', // PDO::MYSQL_ATTR_INIT_COMMAND
                        ],
                    ],
                ],
                'client' => [
                    // This defines an OAuth2 adapter backed by Mongo.
                    'adapter' => 'Laminas\ApiTools\MvcAuth\Authentication\OAuth2Adapter',
                    'storage' => [
                        'adapter' => 'mongo',
                        'locator_name' => 'SomeServiceName', // If provided, pulls the given service
                        'dsn' => 'mongodb://localhost',
                        'database' => 'oauth2',
                        'options' => [
                            'username' => 'username',
                            'password' => 'password',
                            'connectTimeoutMS' => 500,
                        ],
                    ],
                ],
            ],
            /* ... */
        ],
        /* ... */
    ],
    /* ... */
];

class Module
{
    public function onBootstrap($e)
    {
        $app      = $e->getApplication();
        $events   = $app->getEventManager();
        $services = $app->getServiceManager();

        $events->attach(
            'authentication',
            function ($e) use ($services) {
                $listener = $services->get('Laminas\ApiTools\MvcAuth\Authentication\DefaultAuthenticationListener')
                $adapter = $services->get('MyCustomAuthenticationAdapter');
                $listener->attach($adapter);
            },
            1000
        );
    }
}

use Laminas\ServiceManager\DelegatorFactoryInterface;
use Laminas\ServiceManager\ServiceLocatorInterface;

class CustomAuthenticationDelegatorFactory implements DelegatorFactoryInterface
{
    public function createDelegatorWithName(
        ServiceLocatorInterface $services,
        $name,
        $requestedName,
        $callback
    ) {
        $listener  = $callback();
        $listener->attach($services->get('MyCustomAuthenticationAdapter');
        return $listener;
    }
}

return [
    /* ... */
    'service_manager' => [
        /* ... */
        'delegators' => [
            'Laminas\ApiTools\MvcAuth\Authentication\DefaultAuthenticationListener' => [
                'CustomAuthenticationDelegatorFactory',
            ],
        ],
    ],
    /* ... */
];