Drupal how-to: redirect anonymous users to login page | A working example module (Drupal 9 compatible)
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:
- More info on responding to events in Drupal here on Drupalize.me.
- Get current user and facilitate 'account' (this is not dependency injection, see comments).
- Get current request with ->getRequest(), here's what differs from the Drupal 8 version: we couldn't get ->getRouteName() to work properly.
- 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).
- Respond with the redirect to Drupal's login page.
Drupal 8 version
'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!