valentine94
6/22/2016 - 8:46 AM

Remove ALL permissions for anonymous users in Drupal 8

Remove ALL permissions for anonymous users in Drupal 8

<?php
use Drupal\user\Entity\Role;

// Load the anonymous role entity.
$role = \Drupal::entityTypeManager()
  ->getStorage('user_role')
  ->load(Role::ANONYMOUS_ID);
// Ensure role exists.
if (!empty($role) && $role instanceof Role) {
  // Get all permissions array.
  $permissions = $role->getPermissions();
  // Ensure permissions array isn't empty.
  if (!empty($permissions)) {
    // Walk for a permissions array items.
    foreach ($permissions as $permission) {
      // Revoke each permission for this role.
      $role->revokePermission($permission);
    }
    // Save an updated role entity.
    $role->save();
  }
}