0

I implemented a controller class in Drupal 8, which redirects to an external site. If I use \Symfony\Component\HttpFoundation\RedirectResponse, I get this error.

Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

Using \Drupal\Core\Routing\TrustedRedirectResponse, I get this error.

The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early.
Returned object class: \Drupal\Core\Routing\TrustedRedirectResponse

What should I do?

  • 1
    See drupal.org/node/2638686 and the related issues, you need to properly deal with cacheablity metadata, we can't help without seeing your specific code – Berdir Apr 13 '17 at 21:07
1

Define a controller and redirect to external URL.

Use TrustedRedirectResponse class in case you know that you want to redirect to an external URL. Example below:

use Drupal\Core\Controller\ControllerBase; 
use Drupal\Core\Routing\TrustedRedirectResponse; 
class ExampleController extends ControllerBase {

  public function example() {
    return new TrustedRedirectResponse('https://google.com');  
  }
}
0

With a route name on a Controller:

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;
class MyControllerClass extends ControllerBase {

  public function foo() {
    //...
    return $this->redirect('user.page');
  }
}

With a absolute url:

return new RedirectResponse('https://google.com');
  • It did not help for me. At last, I created a class which extends \Drupal\Component\HttpFoundation\SecuredRedirectResponse. It is required to implement isSafe($url) method to do so. In my case, this is sufficient. Thank you for your answer. – MH35 Apr 13 '17 at 6:26
0

Alternatively implement hook_redirect_response_alter() (as per #2909182 patch).

Here is the example from redirect_test.module:

use Drupal\redirect\Entity\Redirect;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Implements hook_redirect_response_alter().
 */
function redirect_test_redirect_response_alter(RedirectResponse $response, Redirect $redirect) {
  $path = 'test/redirect/2/successful';
  $replace = 'test/redirect/other';
  if ($redirect->getRedirect()['uri'] == "internal:/" . $path) {
    $response->setTargetUrl(str_replace($path, $replace, $redirect->getRedirectUrl()->setAbsolute()->toString()));
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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