Module Development

Get Information about the Current User for Drupal 8, 9, 10, and 11

Want to know if the person that's viewing your custom block is authenticated? Need to change the elements visible on the page based on a user's permissions or roles? Want to display a welcome message for users returning to your site?

All of these things require knowing who the user is that's currently accessing a page. This can be accomplished by using the current_user service to load an object that contains information about the current user as well as methods for checking permissions, and retrieving additional information.

In this tutorial we'll:

  • Define what "current user" means
  • Use the current_user service to retrieve an implementation of \Drupal\Core\Session\AccountInterface
  • Retrieve information about, and check the permissions of, the current user

By the end of this tutorial you should be able to retrieve and make use of information about the applications current user in order to perform logic in your code that customizes the response for different users.