Skip to content

Permission based authorization

Marin Călin edited this page Sep 20, 2022 · 1 revision

You can define permission requirements for a specific controller or action by using the predefined [AuthorizePermission] attribute, using the entries from the Permission enum as parameters. This allows you not to rely on volatile role keys when building your code and caters for the need to allow for fully dynamic roles in your application.

For example, the following code limits access to any actions on the AdministrationController to users who have the 'ViewAdmin' permission:

#[AuthorizePermission(Permission::ViewAdmin)]
class AdministrationController extends Controller
{
    public function __invoke()
    {
        //
    }
}

Multiple permissions can be specified as an array:

#[AuthorizePermission([Permission::ViewAdmin, Permission::ViewSalaries])]
class SalaryController extends Controller
{
    public function __invoke()
    {
        //
    }
}

The SalaryController is only accessible by users who either have the 'ViewAdmin' permission or the 'ViewSalaries' permission.

When multiple attributes are applied, an accessing user must have all the permissions specified. The following sample requires that a user must have both the ViewAdmin and the ManageDevices permissions:

#[AuthorizePermission(Permission::ViewAdmin)]
#[AuthorizePermission(Permission::ManageDevices)]
class ControlPanelController extends Controller
{
    public function __invoke()
    {
        //
    }
}

Access to an action can be limited by applying additional permission authorization attributes at the action level:

#[AuthorizePermission(Permission::ViewAdmin)]
#[AuthorizePermission(Permission::ManageDevices)]
class ControlAllPanelController extends Controller
{
    public function setTime() {
        //
    }

    #[AuthorizePermission(Permission::ShutDownDevice)]
    public function shutDown() {
        //
    }
}

In the preceding ControlAllPanelController controller:

  • Users with either the ViewAdmin, or the ManageDevices permission can access the controller and the setTime action.
  • Only users with the ShutDownDevice permission can access the shutDown action.

A controller can be locked down but allow anonymous, unauthenticated access to individual actions:

#[AuthorizePermission(Permission::ViewAdmin)]
class Control3PanelController extends Controller
{
    public function setTime() {
        //
    }

    #[AllowAnonymous]
    public function login() {
        //
    }
}