Inconsistent behavior with user_logout function
-
01-03-2021 - |
Question
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
Solution
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