Drupal how-to: redirect anonymous users to login page | A working example module (Drupal 9 compatible)

Jun 26, 2020

(Available for projects)
Joris Snoek
Freelance Drupal
Consultant & Developer

For our Drupal distribution we needed to redirect all anonymous users to the login page, as for now it's implemented as a closed platform for social collaboration. The Drupal 8 way didn't work anymore; we fixed it for Drupal 9 and published a working module.

So if you're building a Drupal social intranet, collaboration tool or community this might help you to direct them the right way -so they don't get an unfriendly 'access denied'.

Keep in mind that you still have to build the correct access control into all your pages with help of permissions / access checks / advanced route access, this module doesn't provide for that.

Clone and run off

We published the Drupal module here on Github so you can copy it and run off with it to do whatever you need. At the moment it's not a published Drupal.org project with all kinds of configurable stuff.

A short explanation of the code

First you'll have to implement an 'Event Subscriber' in the .services.yml file.

More info: Subscribe to and dispatch events.

Next, it took a while before we figured it out, but this code in /src/EventSubscriber/AnonymousRedirectSubscriber.php is all it takes to make it work:

  1. More info on responding to events in Drupal here on Drupalize.me.
  2. Get current user and facilitate 'account' (this is not dependency injection).
  3. Get current request with ->getRequest(), here's what differs from the Drupal 8 version: we couldn't get ->getRouteName() to work properly.
  4. Check if current user is anonymous, but exclude some paths. Also, we had to facilitate user/reset/* with php's fnmatch, because that path contains a variable (the reset hash).
  5. Respond with the redirect to Drupal's login page.

Drupal 8 version

You can find the previous Drupal 8 code here, and we also found the Anonymous login module, but both didn't work in our Drupal 9 (then beta) install.

'quick-start' Drupal to test

To test this module fast in a fresh install, Drupal's quick-start might come in handy.

Need this as a contrib Drupal module?

Please let me know in comments down below, if there is enough positive feedback on this we might make it configurable and contrib it!

Comments

Need even
more knowlegde?