I am basically trying to do what described in How can I let anonymous users view user profiles by role? in Drupal 8. User profiles should only be visible to anonymous users only if those profiles are for users having a certain role; all the other user profiles should not be accessible to anonymous.

The answer there suggests using hook_user_view(), but it appears that hook has been removed in Drupal 8. Is there a different/correct way to do this now?

3 Answers 3


4k4's link is a really good resource for access checking for custom routes.

Another option would be to implement hook_entity_access in your own custom module. I just tested this and it does what you originally asked for:

 * Implements hook_entity_access().
function  MYMODULE_entity_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account) {
  if ($entity->getEntityType()->id() == 'user' && !$account->id()) {
    if (!$entity->hasRole('administrator')) {
      return \Drupal\Core\Access\AccessResult::forbidden();

Obviously, change administrator with the machine name of the role you are looking to grant access too. You do need to give anonymous users the permsission to view user information also. This just limits the entities (users) they are allowed to view.

  • This worked, thanks! 4k4's tip to add a custom access check on the route as helpful too, but I decided to try this first since it's a little more straightforward to me.
    – Megan
    Commented Oct 17, 2016 at 14:03

hook_user_view() is still available in drupal 8, but the hook naming schema has changed, because the hook can now be used for all entity types:


A more D8 way to do this could be a custom access check on the route:



Anonymous is a default role in Drupal 8. Still if you want to create custom roles and then want all users belongs to that group, view users profile info, following steps can be followed:

  1. Login to Admin panel
  2. Click on People
  3. Click on Roles and create Custom Role
  4. Click on Permissions
  5. Search for "View user information"
  6. Assign role for this entry to your custom role.

This link can be helpful

  • I think you misread the question. Megan is asking how to allow anonymous users to view some user profiles. Your answer only works for logged in users, and would allow access to every user profile.
    – Chance G
    Commented Oct 14, 2016 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.