Drupal 8 development: always redirect all logged out visitors to the login page

Joris Snoek
Lucius Digital | Blog
2 min readFeb 12, 2018
Login or get out!

Currently we are busy constructing the production of a realtime messaging platform in Drupal and NodeJS, look at it as a ‘WhatsApp for Business’. This Drupal system works like a web app; logging in is mandatory. How do you make sure that logged out visitors must log in to Drupal 8 before they are allowed to continue?

Drupal has many out-of-the-box functionalities, as well as a powerful API, but because it has so many functions many tracks are standardly available for anonymous visitors. We’d want to make all paths unreachable, until you log in.

That means that visitors always will be redirected to the login screen as long as they aren’t logged in. You wouldn’t want an anonymous user reaching internal news on the homepage.

Redirect URL in Drupal 8

Basically, we want all url’s / paths be made unavailable for non-logged in visitors, except explicitly specified pages like:

  • Login (/user)
  • Forgot password (/user/password)
  • Login link (user/reset/login)

in Drupal 7 you could use the module Logintoboggan for that purpose. You could also easily work around it in hook_init() or hook_boot() in a custom Drupal 7 module.

Quest

This was quite a puzzle, and we soon found some examples as well as exceptions. Everytime it didn’t work how we wanted it to. This example was the most useful.

Implementation in Drupal 8

Eventually, we got it working with the help of following code in a custom Drupal 8 module:

services.yml

put this file in your module root, and format yourmodulename.services.yml:

RedirectAnonymousSubscriber.php

Put the file RedirectAnonymousSubscriber.php in folder /src/EventSubscriber/ and do your custom thing:

This code builds on symfony’s EventSubscriber, the framework on which Drupal8 has been built.

Wrap up

Alright, that’s it. I hope the information as described will help you to always redirect visitors to the login page. Questions or feedback? Let me know!

--

--