I'm having an issue with writing a redirect based on whether or not the current user's role matches the one listed or not

I've been trying to find solutions related to getting the current path for Drupal 8. I'm not sure if that is one of the issues or not.

class FacultyStaffRedirectSubscriber implements EventSubscriberInterface {

  public function checkForRedirection(GetResponseEvent $event) {
    $request = \Drupal::request();
    $requestUrl = \Drupal::service('path.current')->getPath();
    $current_user = \Drupal::currentUser();
    $roles = $current_user->getRoles();

    if ($requestUrl == '/faculty-staff') {
        if (
          !in_array('faculty', $roles) ||
          !in_array('staff', $roles)
        ) {

            $path =  '/404';
        $response = new RedirectResponse($path);
 public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;


What I'm wanting is to redirect a user to 404 if they attempt to access the path without having the proper role assigned to them. Currently, nothing happens at all and logged in users can see the page.

  • 1
    Possible duplicate of Returning alternate HTTP codes for unpublished content in Drupal 8
    – leymannx
    Jun 25, 2019 at 17:30
  • Shouldn't the question rather be "How can I return a 404 when a user with a certain role tries to access a certain route?"
    – leymannx
    Jun 25, 2019 at 17:34
  • 3
    You should never check against a role to action something, break it down to permission level and assign the permission to the roles that need this.
    – baikho
    Jun 25, 2019 at 21:38
  • Few remarks you could improve (little bit off topic). 1. Request can be always fetched from this event with 'getRequest()'. 2.Instead of URL you should always compare the route name. This is also present in the Request object. 3. You can always inject services (such as current user) to event subscribers. I would suggest so. 4. Instead of sending the response by yourself and returning, you could you the event's setResponse() method.
    – ssibal
    Jun 26, 2019 at 7:26
  • @baikho, I got it working by taking your suggestion. I found a module called view access per node: drupal.org/project/vapn It works in conjunction with the code above above by setting permission options on the content type and allowing access based on the individual page nodes as you manually chose user roles for access on each one. Jun 27, 2019 at 17:10


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.