3 namespace Drupal\Component\HttpFoundation;
5 use Symfony\Component\HttpFoundation\RedirectResponse;
8 * Provides a common base class for safe redirects.
10 * In case you want to redirect to external URLs use
11 * TrustedRedirectResponse.
13 * For local URLs we use LocalRedirectResponse which opts
14 * out of external redirects.
16 abstract class SecuredRedirectResponse extends RedirectResponse {
19 * Copies an existing redirect response into a safe one.
21 * The safe one cannot accidentally redirect to an external URL, unless
22 * actively wanted (see TrustedRedirectResponse).
24 * @param \Symfony\Component\HttpFoundation\RedirectResponse $response
25 * The original redirect.
29 public static function createFromRedirectResponse(RedirectResponse $response) {
30 $safe_response = new static($response->getTargetUrl(), $response->getStatusCode(), $response->headers->allPreserveCase());
31 $safe_response->fromResponse($response);
32 return $safe_response;
36 * Copies over the values from the given response.
38 * @param \Symfony\Component\HttpFoundation\RedirectResponse $response
39 * The redirect reponse object.
41 protected function fromResponse(RedirectResponse $response) {
42 $this->setProtocolVersion($response->getProtocolVersion());
43 $this->setCharset($response->getCharset());
44 // Cookies are separate from other headers and have to be copied over
46 foreach ($response->headers->getCookies() as $cookie) {
47 $this->headers->setCookie($cookie);
54 public function setTargetUrl($url) {
55 if (!$this->isSafe($url)) {
56 throw new \InvalidArgumentException(sprintf('It is not safe to redirect to %s', $url));
58 return parent::setTargetUrl($url);
62 * Returns whether the URL is considered as safe to redirect to.
65 * The URL checked for safety.
69 abstract protected function isSafe($url);