Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 37 ยท Users, Roles and Security

Roles and Permissions

Manage Drupal users, roles and permissions: the built-in roles, defining module permissions in permissions.yml, checking access in code and a role-based access stand-in.

Who may do what is the heart of a Drupal site's security. Drupal's model is simple and powerful: users have roles, and roles hold permissions. A permission is a single named ability such as access content, create article content or administer users. You never give permissions to a user directly. Instead you decide which roles exist and which permissions each has, then assign roles to people.

Drupal cannot run on this site, so the YAML and PHP are read-only. JavaScript stand-ins model the same rules.

Built-in roles

Every site starts with three:

  • Anonymous user: everyone who is not logged in. Permissions here apply to the public.
  • Authenticated user: every logged-in account. It is the baseline: all authenticated users get these permissions in addition to their other roles.
  • Administrator: a role flagged is_admin, which automatically holds every permission (including those added by modules installed later).

Create additional roles on People > Roles, such as editor, moderator or member. Grant permissions on People > Permissions (a grid of permissions by role, or per role). Users receive roles on their edit page, or with Drush:

Terminal
drush user:create anna --mail="[email protected]" --password="CHANGE-ME"
drush user:role:add editor anna
drush user:role:remove editor anna
drush role:perm:add editor 'create article content,edit own article content'
drush user:information anna
drush user:login --name=anna     # one-time login link

User 1, created during installation, bypasses all access checks. Use it only for emergencies and give people their own accounts with the roles they need.

Principle of least privilege

Give each role only what is needed. Be careful with permissions marked "Warning: Give to trusted roles only", such as administer permissions, use PHP for settings (removed from core), bypass node access, administer modules and administer users. The admin role can change anything, so keep the number of administrators small.

Node.js Stand-in: roles, permissions and the administrator flag

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.

Defining permissions in a module

In tutorial_notes.permissions.yml:

YAML
administer tutorial notes:
  title: 'Administer tutorial notes'
  description: 'Change notes settings and delete any note.'
  restrict access: true

view private notes:
  title: 'View private notes'

edit own notes:
  title: 'Edit own notes'

restrict access: true shows the warning on the permissions page. A module can also generate permissions dynamically with a callback class (this is how "create X content" appears for each content type):

YAML
permission_callbacks:
  - \Drupal\tutorial_notes\NotePermissions::forTypes
PHP
public function forTypes(): array {
  $permissions = [];
  foreach (['public', 'private'] as $kind) {
    $permissions["view $kind notes"] = ['title' => "View $kind notes"];
  }
  return $permissions;
}

Use permissions in routes (_permission: 'view private notes'), as shown in routes and controllers.

Checking access in code

The current user is a service (current_user) and implements AccountInterface:

PHP
$account = \Drupal::currentUser();

if ($account->hasPermission('view private notes')) { /* ... */ }
if ($account->isAuthenticated()) { /* logged in */ }
if (in_array('editor', $account->getRoles())) { /* has the role */ }

Prefer checking permissions rather than role names, because site builders may rename or restructure roles but permission names are stable. In a template you rarely check at all: Drupal's field and block access already hides things the user may not see.

For blocks and controllers return an AccessResult (the access API, with cacheability):

PHP
use Drupal\Core\Access\AccessResult;

return AccessResult::allowedIfHasPermission($account, 'view private notes');

Access results are cached, so the user's permissions must also be reflected in cache contexts (user.permissions). AccessResult::allowedIfHasPermission() adds it for you. More about this in access control.

Node.js Stand-in: access result with cache context

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.

Configuration and roles

Roles and their permissions are configuration (user.role.editor.yml), so they export with the rest of the site. Install a role from a module in config/install/user.role.notes_manager.yml:

YAML
langcode: en
status: true
dependencies:
  module:
    - tutorial_notes
id: notes_manager
label: 'Notes manager'
weight: 5
is_admin: false
permissions:
  - 'administer tutorial notes'

Registration and account settings

On Configuration > People > Account settings choose who can register (administrators only, visitors, or visitors with approval), email verification and the text of automated emails. Public registration plus unreviewed permissions is a common source of spam and abuse, so keep the authenticated role minimal and consider CAPTCHA/honeypot modules.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement about permissions is true?

    Drupal assigns permissions to roles, then roles to users.
  2. 2. What does the authenticated user role represent?

    Every logged-in account has it in addition to any other roles.
  3. 3. Why check permissions rather than role names in code?

    Permission names are part of your module's API; role names belong to the site builder.
  4. 4. Where do you define a module permission?

    Permission machine names are declared in MODULE.permissions.yml.

Summary

  • Users have roles; roles hold permissions; user 1 and the administrator role bypass checks.
  • Give roles the fewest permissions possible and keep administrators few.
  • Modules declare permissions in permissions.yml or via callbacks.
  • Check permissions (not role names) in code and return AccessResult with cache metadata.
  • Roles are configuration and can be exported and installed by modules.

Next: Security Practices