Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 37 ยท Users, Roles and Security

Access Control and Entity Access

Control who can view, edit and delete content in Drupal: entity access hooks, AccessResult, custom access checkers, node grants, content moderation and access stand-ins.

Permissions answer "may this role do this kind of thing?" Many real sites need finer questions: may this user edit this article, view this private note, or see this field? Drupal answers them with the access API. Every operation on an entity or field asks the system, which collects opinions from the entity's own handler, from modules and from the node access system, and combines them.

Drupal cannot run on this site; the PHP is read-only. The stand-ins model the combination rules in JavaScript.

Three possible answers

An access check returns an AccessResult with one of three states:

  • Allowed: this check says yes.
  • Forbidden: this check says no, and nothing can override it.
  • Neutral: this check has no opinion.

When several checks run, the results are combined with orIf() (used for entity access: forbidden wins, then allowed, otherwise neutral) or andIf() (all must allow). If the final answer is neutral, access is denied: you must be allowed by someone. That is why a module that does not care returns neutral rather than forbidden.

Node.js Stand-in: combining allowed, neutral, forbidden

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Entity access

Each entity type has an access control handler. For nodes, $node->access('update', $account) asks whether the account may edit. Core combines the user's permissions ("edit own article content", "edit any article content", "bypass node access"), the published state and node grants. In code:

PHP
if ($node->access('view')) { /* current user */ }
if ($node->access('update', $account)) { /* a specific account */ }
$access = $node->access('delete', NULL, TRUE); // returns an AccessResult for cache metadata

Whenever you list entities, use queries with access checks (->accessCheck(TRUE)) so users do not see items they should not. Views does this by default and can add a filter "Published (= Yes) or admin".

Altering entity access from a module

hook_ENTITY_TYPE_access adds your opinion about a specific entity type:

PHP
<?php

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Implements hook_node_access().
 */
function tutorial_notes_node_access(EntityInterface $node, $operation, AccountInterface $account) {
  if ($node->bundle() !== 'note') {
    return AccessResult::neutral();
  }
  if ($node->hasField('field_private') && $node->get('field_private')->value) {
    $is_owner = $node->getOwnerId() === $account->id();
    return AccessResult::forbiddenIf(!$is_owner && !$account->hasPermission('view private notes'))
      ->addCacheableDependency($node)
      ->cachePerUser();
  }
  return AccessResult::neutral();
}

Return neutral for everything you do not handle, and attach cache metadata (addCacheableDependency, cachePerUser, cachePerPermissions) so the result is cached correctly.

Custom access for routes

For route-specific rules, write an access check method and refer to it in the route:

YAML
tutorial_notes.edit_own:
  path: '/notes/{node}/quick-edit'
  defaults:
    _controller: '\Drupal\tutorial_notes\Controller\NotesController::quickEdit'
  requirements:
    _custom_access: '\Drupal\tutorial_notes\Access\NoteAccess::check'
  options:
    parameters:
      node:
        type: entity:node
PHP
public function check(AccountInterface $account, NodeInterface $node): AccessResultInterface {
  return AccessResult::allowedIf($node->bundle() === 'note' && $node->getOwnerId() === $account->id())
    ->addCacheableDependency($node)
    ->cachePerUser();
}

Other ready-made route checks: _entity_access: 'node.update', _role, _permission, _user_is_logged_in. A service tagged access_check can implement reusable custom requirements.

Field access

A field can be hidden or made read-only per user with hook_entity_field_access. Because Drupal asks for each field, even a form or a Views listing will respect it:

PHP
function tutorial_notes_entity_field_access($operation, $field_definition, $account, $items = NULL) {
  if ($field_definition->getName() === 'field_internal_note' && $operation === 'view') {
    return AccessResult::forbiddenIf(!$account->hasPermission('view internal notes'))->cachePerPermissions();
  }
  return AccessResult::neutral();
}

Node access grants

For content that must be restricted by who the viewer is (a members-only section, per-group visibility), core has node grants. A module records which "realms" and IDs may view/update/delete each node (hook_node_access_records), and tells Drupal which grants the current user holds (hook_node_grants). Listings and searches then filter automatically through the node_access table. Contributed modules such as Group, Organic Groups, Content Access and Permissions by Term build on it. Two things to remember: grants only apply when a node access module exists, and the bypass node access permission skips them.

Node.js Stand-in: node grants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Workflows and content moderation

Core's Workflows and Content Moderation modules add states (Draft, In review, Published, Archived) and transitions, each guarded by permissions such as use editorial transition publish. Combine them with roles (writer, reviewer, publisher) to give editors a clear flow without custom code. The moderation state is a field on the node, so access hooks and Views can read it.

Testing access

Log in as different users with drush user:login --name=NAME, or use a private browser window. Write a kernel or functional test that creates users with roles and asserts $node->access('view', $user). Always test the anonymous user and a user with no roles: access bugs usually show up there.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when every access check returns neutral?

    Neutral means no opinion; someone must explicitly allow access.
  2. 2. Which result can never be overridden by another module's allowed result?

    Forbidden wins when results are combined with orIf.
  3. 3. When listing nodes with an entity query, what must you set?

    Drupal requires you to decide whether the query respects access.
  4. 4. Why attach cache metadata to access results?

    Access results are cached, so dependencies and contexts must be recorded.

Summary

  • Access checks return allowed, neutral or forbidden; all-neutral means denied.
  • Use $entity->access(), hook_ENTITY_TYPE_access and field access for fine-grained rules.
  • Custom route access uses _custom_access or an access_check service.
  • Node grants filter listings by viewer; Content Moderation adds editorial states.
  • Always add cache metadata and test with several users.

Next: Configuration Management and Deployment