1

For a drupal 8 site, I have a custom function that does the following:

It logs out the user and sends them to an external url

Inside the controller CustomController, I have:

function custom_logout(){
 if (\Drupal::currentUser()->isAuthenticated()) {
    user_logout();
    return new TrustedRedirectResponse('https://example.com');
 }
}

In the routing.yml

customl.clogout:
  path: '/customlogout'
  defaults:
    _controller: '\Drupal\user\Controller\CustomController::custom_logout'
  requirements:
    _user_is_logged_in: 'TRUE'
    

When I visit the /customlogout for the first time it logs me out of Drupal and redirects me to example.com. If I revisit my site and login in again, and repeat the process it still redirects me to example.com but when I check my site I am still logged in. I am wondering why this happens? I can still logout using /user/logout though

Thank you

3
  • How exactly do you call this function, what function actually, and from where? An event subscriber? Can you please update your question for clarification?
    – leymannx
    Commented Dec 14, 2020 at 22:01
  • Thank you, I have updated the question
    – Aves2432
    Commented Dec 14, 2020 at 22:09
  • I assume that this issue is caused by this line return new TrustedRedirectResponse('example.com'). Do we have any alternative that guarantees logout
    – Aves2432
    Commented Dec 14, 2020 at 22:15

1 Answer 1

5

As it turns out,

return new TrustedRedirectResponse('https://example.com');

was the culprit here. TrustedRedirectResponse extends CacheableSecuredRedirectResponse, as a result the function was cached, and user_logout was not called even when I visited the /customlogout

The workaround for this is adding the following lines in your routing.yml

options:
    
  no_cache: TRUE 

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.