How do I grant to roles dynamically created permissions? In my module, I am dynamically creating user permissions for vocabularies. I would like to also grant all roles the view permission, but I cannot figure out a proper way where to do it.

I cannot use a config yml, because these are dynamic permissions created within permission callback and both the hook_install and hook_modules_installed are run before the permission callback, so the roles don't pick up the permissions. 

This is how I tried to grant the permissions in hook_install() and hook_modules_installed().

$vocabularies = \Drupal::entityTypeManager()
  -&gt;getStorage('taxonomy_vocabulary')
  -&gt;loadMultiple();

if (!empty($vocabularies)) {
  foreach ($vocabularies as $vocabulary) {
    $permission = 'view name defined in the callback ' . $vocabulary-&gt;id();
    $anonymous_rid = RoleInterface::ANONYMOUS_ID;
    $authenticated_rid = RoleInterface::AUTHENTICATED_ID;

    if ($anonymous_role = Role::load($anonymous_rid)) {
      $anonymous_role-&gt;grantPermission($permission);
    }
    if ($authenticated_role = Role::load($authenticated_rid)) {
      $authenticated_role-&gt;grantPermission($permission);
    }
  }
}


Where should I grant these permissions within my module?
After granting the permissions, you should call the save() method to make the code work.

if ($anonymous_role = Role::load($anonymous_rid)) {
  $anonymous_role-&gt;grantPermission($permission);
  $anonymous_role-&gt;save();
}