Skip to content

Latest commit

 

History

History
152 lines (115 loc) · 4.26 KB

05. Strategies.md

File metadata and controls

152 lines (115 loc) · 4.26 KB

Strategies

In this section, you will learn:

  • What are strategies
  • How to use built-in strategies
  • Creating custom strategies

What are strategies?

A strategy is an object that listens to the MvcEvent::EVENT_DISPATCH_ERROR event. It is used to describe what happens when an access to a resource is unauthorized by ZfcRbac.

ZfcRbac strategies all check if an ZfcRbac\Exception\UnauthorizedExceptionInterface has been thrown.

By default, ZfcRbac does not register any strategy for you. The best place to register it is in your onBootstrap method of the Module.php class:

public function onBootstrap(EventInterface $e)
{
    $t = $e->getTarget();

    $t->getEventManager()->attach(
        $t->getServiceManager()->get('ZfcRbac\View\Strategy\UnauthorizedStrategy')
    );
}

Built-in strategies

ZfcRbac comes with two built-in strategies: RedirectStrategy and UnauthorizedStrategy.

RedirectStrategy

This strategy allows to redirect any unauthorized request to another route, by optionally appending the previous URL as a query param.

To register it, copy-paste this code in your Module.php class:

public function onBootstrap(EventInterface $e)
{
    $t = $e->getTarget();

    $t->getEventManager()->attach(
        $t->getServiceManager()->get('ZfcRbac\View\Strategy\RedirectStrategy')
    );
}

You can configure the strategy using the redirect_strategy subkey:

return [
    'zfc_rbac' => [
        'redirect_strategy' => [
            'redirect_when_connected'        => true,
            'redirect_to_route_connected'    => 'home',
            'redirect_to_route_disconnected' => 'login',
            'append_previous_uri'            => true,
            'previous_uri_query_key'         => 'redirectTo'
        ],
    ]
];

If a user tries to access to an unauthorized resource (eg.: http://www.example.com/delete), he/she will be redirect to the "login" route if is not connected and to the "home" route otherwise (it must exists in your route config, of course) with the previous URL appended : http://www.example.com/login?redirectTo=http://www.example.com/delete

You can prevent redirection when a user is connected (i.e. so that the user gets a 403 page) by setting redirect_when_connected to false.

UnauthorizedStrategy

This strategy allows to render a template on any unauthorized request.

To register it, copy-paste this code in your Module.php class:

public function onBootstrap(EventInterface $e)
{
    $t = $e->getTarget();

    $t->getEventManager()->attach(
        $t->getServiceManager()->get('ZfcRbac\View\Strategy\UnauthorizedStrategy')
    );
}

You can configure the strategy using the unauthorized_strategy subkey:

return [
    'zfc_rbac' => [
        'unauthorized_strategy' => [
            'template' => 'error/custom-403'
        ],
    ]
];

By default, ZfcRbac uses a template called error/403.

Creating custom strategies

Creating a custom strategy is rather easy. Let's say we want to create a strategy that integrates with the ApiProblem Zend Framework 2 module:

namespace Application\View\Strategy;

use Zend\Http\Response as HttpResponse;
use Zend\Mvc\MvcEvent;
use ZF\ApiProblem\ApiProblem;
use ZF\ApiProblem\ApiProblemResponse;
use ZfcRbac\View\Strategy\AbstractStrategy;
use ZfcRbac\Exception\UnauthorizedExceptionInterface;

class ApiProblemStrategy extends AbstractStrategy
{
    public function onError(MvcEvent $event)
    {
        // Do nothing if no error or if response is not HTTP response
        if (!($exception = $event->getParam('exception') instanceof UnauthorizedExceptionInterface)
            || ($result = $event->getResult() instanceof HttpResponse)
            || !($response = $event->getResponse() instanceof HttpResponse)
        ) {
            return;
        }

        return new ApiProblemResponse(new ApiProblem($exception->getMessage()));
    }
}

Register your strategy:

public function onBootstrap(EventInterface $e)
{
    $e->getTarget()
      ->getEventManager()
      ->attach(new ApiProblemStrategy());
}

Navigation

  • Continue to [the Authorization Service](/docs/06. Using the Authorization Service.md)
  • Back to [the Guards](/docs/04. Guards.md)
  • Back to the Index