Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

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

Parent Feed: 

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.

drupal event subscriber

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:

Drupal anonymous redirect subscriber

  1. More info on responding to events in Drupal here on Drupalize.me.
  2. Get current user with 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!

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web