Restricting Access to Drupal 8 Controllers

Controllers in Drupal 8 are the equivalent of hook_menu in Drupal 7. A controller lets you define a URL and what content or data should appear at that URL. If you’re like me, limiting access to my controllers is sometimes an afterthought. Limiting access is important because it defines who can and can’t see a page.
Controllers are defined in a YAML file called module_name.routing.yml. Access and permission rules are defined in the the module_name.routing.yml under _requirements. Most of the code examples will be from a module_name.routing.yml file added to my_module in the top level.
Note: There is a lot of existing documentation on how to create controllers in Drupal 8, so I won’t focus on that here.
I’ve outlined some of the most useful approaches for limiting access below. You can jump straight to the most relevant section using the following links: limit by permission, limit by role, limit by one-off custom code, limit by custom access service.

Limit by permission

In this case, a permission from the Drupal permissions page is given. Permissions can be found at /admin/people/permissions. Finding the exact permission name can be tricky. Look for module.permissions.yml files in the module providing the permission.

<br />
my_module.dashboard:<br />
  path: 'dashboard'<br />
  defaults:<br />
    _controller: '\Drupal\my_module\Controller\DashboardController::content'<br />
    _title: 'Dashboard'<br />
  requirements:<br />
    _permission: 'access content'<br />

Key YAML definition:
<br />
_permission: 'THE PERMISSION NAME'<br />

Limit by role

You can also limit access by role. This would be useful in cases where users of a specific role will be the only ones needing access to your controller. You can define user roles at /admin/people/roles.

<br />
my_module.dashboard:<br />
  path: 'dashboard'<br />
  defaults:<br />
    _controller: '\Drupal\my_module\Controller\DashboardController::content'<br />
    _title: 'Dashboard'<br />
  requirements:<br />
    _role: 'administrator'<br />

Key YAML definition:
<br />
_role: 'THE ROLE NAME'<br />

You can specify multiple roles using "," for AND and "+" for OR logic.

Limit by one-off custom code

In cases where you have custom access requirements, adding an access method to your controller might make sense. In this example, the page should not be viewed before a specified date.

<br />
my_module.dashboard:<br />
  path: 'dashboard'<br />
  defaults:<br />
    _controller: '\Drupal\my_module\Controller\DashboardController::content'<br />
    _title: 'Dashboard'<br />
  requirements:<br />
   _custom_access: '\Drupal\my_module\Controller\DashboardController::access<br />

Key YAML definition:
<br />
_custom_access: '\Drupal\my_module\Controller\DashboardController::access<br />

The access method in my controller would look like:
<br />
<?php<br />
namespace Drupal\my_module\Controller;</p>
<p>use Drupal\Core\Access\AccessResult;<br />
use Drupal\Core\Controller\ControllerBase;</p>
<p>/<strong><br />
 * Defines the Dashboard controller.<br />
 */<br />
class DashboardController extends ControllerBase { {</p>
<p> /</strong><br />
  * Returns content for this controller.<br />
  */<br />
 public function content() {<br />
   $build = [];<br />
   return $build;<br />
 }</p>
<p> /**<br />
  * Checks access for this controller.<br />
  */<br />
 public function access() {<br />
   // Don’t allow access before Friday, November 25, 2016.<br />
   $today = date("Y-m-d H:i:s");<br />
   $date = "2016-11-25 00:00:00";<br />
   if ($date < $today) {<br />
     // Return 403 Access Denied page.<br />
     return AccessResult::forbidden();<br />
    }<br />
    return AccessResult::allowed();<br />
  }<br />
}<br />

Limit by custom access service

This is similar to having an access method in your controller, but allows the code to be reused across many controllers. This is ideal when you are doing the same access check across many controllers.

<br />
my_module.dashboard:<br />
  path: 'dashboard'<br />
  defaults:<br />
    _controller: '\Drupal\my_module\Controller\DashboardController::content'<br />
    _title: 'Dashboard'<br />
  requirements:<br />
    _custom_access_check: 'TRUE'<br />

Key YAML definition:
<br />
_custom_access_check: 'TRUE'<br />

Proving the _custom_access_check service requires creating two files in my_module.
my_module/my_module.services.yml (defines the Access service and where to find our Access class)
<br />
services:<br />
  my_module.custom_access_check:<br />
    class: Drupal\my_module\Access\CustomAccessCheck<br />
    arguments: ['@current_user']<br />
    tags:<br />
      - { name: access_check, applies_to: _custom_access_check }<br />

my_module/src/Access/CustomAccessCheck.php
<br />
<?php<br />
namespace Drupal\my_module\Access;</p>
<p>use Drupal\Core\Access\AccessResult;<br />
use Drupal\Core\Routing\Access\AccessInterface;<br />
use Drupal\Core\Session\AccountInterface;</p>
<p>/<strong><br />
 * Class CustomAccessCheck.<br />
 *<br />
 * @package Drupal\my_module\Access<br />
 */<br />
class CustomAccessCheck implements AccessInterface {</p>
<p>  /</strong><br />
   * A custom access check.<br />
   *<br />
   * @param \Drupal\Core\Session\AccountInterface $account<br />
   *   Run access checks for the logged in user.<br />
   */<br />
  public function access(AccountInterface $account) {<br />
    // User has a profile field defining their favorite color.<br />
    if ($account->field_color->hasField() && !$account->field_color->isEmpty() && $account->field_color->getString() === 'blue') {<br />
      // If the user's favorite color is blue, give them access.<br />
      return AccessResult::allowed();<br />
    }<br />
    return AccessResult::forbidden();<br />
  }</p>
<p>}<br />

While the above covers some of the most useful ways to restrict access to a controller, there are additional options. Drupal.org has a couple of good resources including Structure of Routes and Access Checking on Routes.

Code Drupal Drupal 8 Drupal Planet

Read This Next