
In Drupal, an access check doesn’t only answer “yes” or “no”. It also answers for whom and for how long that answer holds. Forget the second part, and a decision computed for an administrator may be served from cache to an ordinary visitor.
This article covers custom access checkers, the logic of AccessResult, its cache metadata, and the often misunderstood difference between hook_entity_access and node grants.
AccessResult: three states, not two
Every modern access check returns an AccessResultInterface, with three possible states:
- allowed: I grant access;
- neutral: I have no opinion;
- forbidden: I deny access, and nobody can override it.
They are combined with two operators:
orIf() |
andIf() |
|
|---|---|---|
| One of them is forbidden | forbidden | forbidden |
| At least one allowed | allowed | neutral if the other is neutral |
| Both allowed | allowed | allowed |
| Both neutral | neutral | neutral |
This is what lets several modules vote on the same access: hook_entity_access results are combined with orIf(), and a single forbidden is enough to close the door. Depending on the context, a final neutral counts as a denial: that’s the case for route access, which requires allowed.
Above all, orIf() and andIf() merge the cache metadata of the results that took part in the decision. An access result is a cacheable object, just like a render array.
A custom access checker
Use case: a project management site. The /project/{node}/reports page must be accessible to project members (a field_members field referencing users) and to administrators.
The route
# my_module.routing.yml
my_module.project_reports:
path: '/project/{node}/reports'
defaults:
_controller: '\Drupal\my_module\Controller\ProjectReportsController::view'
_title: 'Reports'
requirements:
_project_member: 'TRUE'
options:
parameters:
node:
type: entity:node
The service
# my_module.services.yml
services:
my_module.project_member_access:
class: Drupal\my_module\Access\ProjectMemberAccessCheck
tags:
- { name: access_check, applies_to: _project_member }
The access_check tag with applies_to binds the service to the _project_member key in requirements. Every route declaring that key goes through it.
The class
<?php
namespace Drupal\my_module\Access;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;
final class ProjectMemberAccessCheck implements AccessInterface {
public function access(AccountInterface $account, NodeInterface $node): AccessResultInterface {
if ($node->bundle() !== 'project') {
return AccessResult::forbidden('Not a project.')->addCacheableDependency($node);
}
$is_member = in_array(
$account->id(),
array_column($node->get('field_members')->getValue(), 'target_id')
);
return AccessResult::allowedIfHasPermission($account, 'administer projects')
->orIf(
AccessResult::allowedIf($is_member)
->addCacheContexts(['user'])
->addCacheableDependency($node)
);
}
}
The arguments of access() are resolved by name and type: $account receives the current user, $node the route parameter already upcast to an entity. You can also ask for RouteMatchInterface $route_match, Route $route or Request $request.
The real topic: cache metadata
Let’s read the code again from a caching point of view:
allowedIfHasPermission()automatically adds theuser.permissionscontext.allowedIf($is_member)knows nothing about how$is_memberwas computed. It’s up to you to say that the result depends on the user (user) and the node (addCacheableDependency($node), which adds thenode:42tag).- Without
addCacheableDependency($node), removing a member from the project would not invalidate results already in cache.
Where it leaks in practice
Route access itself isn’t cached as is. The leak happens when that result is used to build output: a “View reports” link in a block, a menu, a teaser.
// ❌ The boolean loses all cache metadata.
$url = Url::fromRoute('my_module.project_reports', ['node' => $node->id()]);
if ($url->access()) {
$build['reports'] = Link::fromTextAndUrl($this->t('Reports'), $url)->toRenderable();
}
This block is cached without the user context. The first user to display it decides for everyone: if it’s a member, every visitor sees the link; otherwise, no member sees it.
// ✅ The AccessResult object goes into #access, and the renderer merges its cacheability.
$url = Url::fromRoute('my_module.project_reports', ['node' => $node->id()]);
$build['reports'] = Link::fromTextAndUrl($this->t('Reports'), $url)->toRenderable();
$build['reports']['#access'] = $url->access(NULL, TRUE);
The second argument TRUE to access() asks for an AccessResultInterface object instead of a boolean. The renderer accepts that object in #access and adds its contexts and tags to the output. The same rule applies to $entity->access('update', NULL, TRUE).
And if the result isn’t used in a render array? Apply it explicitly:
CacheableMetadata::createFromObject($access)->applyTo($build);
Picking the right context
| Context | Varies by | Cardinality |
|---|---|---|
user.permissions |
The set of permissions | Low |
user.roles |
Roles | Low |
user.roles:editor |
Having the editor role |
2 variants |
user |
The user | One variant per user |
The user context is correct but expensive: it triggers auto-placeholdering (see the article on lazy builders). If access depends on data shared by many users (a team, an organisation), a custom cache context (a service tagged cache.context) sharply reduces the number of variants.
hook_entity_access vs node grants
This is the most common confusion, and it causes real data leaks.
hook_entity_access: case-by-case decisions
function my_module_node_access(NodeInterface $node, $operation, AccountInterface $account) {
if ($operation === 'view' && $node->bundle() === 'project') {
$members = array_column($node->get('field_members')->getValue(), 'target_id');
return AccessResult::forbiddenIf(!in_array($account->id(), $members))
->addCacheContexts(['user'])
->addCacheableDependency($node);
}
return AccessResult::neutral();
}
This hook is called when a specific entity is checked: displaying a page, $node->access(), rendering an entity. It is not called when a query lists entities. A “Latest projects” view will therefore show the titles of projects the user is not a member of, even though they get a 403 when clicking.
Also note that hook_node_access() is not invoked for users with the bypass node access permission.
Node grants: decisions applied to queries
The grants system (hook_node_access_records() + hook_node_grants()) stores permissions in the node_access table. Drupal automatically injects them into every query tagged node_access, which includes entity queries with accessCheck(TRUE) and Views (unless “Disable SQL rewriting” is checked).
function my_module_node_access_records(NodeInterface $node) {
if ($node->bundle() !== 'project') {
return [];
}
$grants = [];
foreach ($node->get('field_members') as $item) {
$grants[] = [
'realm' => 'project_member',
'gid' => $item->target_id,
'grant_view' => 1,
'grant_update' => 0,
'grant_delete' => 0,
];
}
return $grants;
}
function my_module_node_grants(AccountInterface $account, $operation) {
return ['project_member' => [$account->id()]];
}
The price: grants are precomputed. Changing the logic means rebuilding permissions (node_access_rebuild()), a long operation on a large site. And they only apply to nodes.
What about other entities?
For entities other than nodes, entity queries with accessCheck(TRUE) add the {entity_type}_access tag (for example media_access). You can filter listings with hook_query_TAG_alter(), or use the contrib Entity API module, which provides generic “query access” (the entity.query_access event) for entity types that opt in.
Drupal 10: an entity query on a content entity must call
->accessCheck(TRUE)or->accessCheck(FALSE)explicitly, otherwise an exception is thrown. It’s a good time to review everyaccessCheck(FALSE)in your code: each one is a listing that ignores permissions.
Summary
| Need | Tool |
|---|---|
| Protect a route | Access checker (_custom_access or the access_check tag) |
| Decide access to a displayed entity | hook_entity_access / hook_ENTITY_TYPE_access |
| Filter lists of nodes | Node grants |
| Filter lists of other entities | hook_query_TAG_alter() on {entity_type}_access |
Testing access and its cacheability
A Kernel test can check both at once:
public function testMemberAccess(): void {
$member = $this->createUser();
$stranger = $this->createUser();
$project = $this->createNode(['type' => 'project', 'field_members' => [$member->id()]]);
$check = new ProjectMemberAccessCheck();
$result = $check->access($member, $project);
$this->assertTrue($result->isAllowed());
$this->assertContains('user', $result->getCacheContexts());
$this->assertContains('node:' . $project->id(), $result->getCacheTags());
$this->assertFalse($check->access($stranger, $project)->isAllowed());
}
Assertions on contexts and tags are the ones most often missing, yet they are what protects you from leaks in production.
Conclusion
Correct access control in Drupal has two dimensions: the decision, and its cacheability. Return AccessResult objects rather than booleans, always declare what the decision depends on, and choose between hook_entity_access and node grants depending on whether you protect one entity or a list. Three simple reflexes that prevent the most common holes in Drupal sites.
