HttpFoundation: Request, Response and signed URLs in Symfony
Symfony's HttpFoundation component turns HTTP into objects: a Request for what comes in, a Response for what goes out, headers and caching included.
public function article(Article $article, Request $request): Response { $page = $request->query->getInt('page', 1); // ?page=, as an integer $langue = $request->headers->get('Accept-Language'); // a header $response = $this->render('journal/article.html.twig', ['article' => $article]); $response->setPublic()->setMaxAge(300); // Cache-Control: public, max-age=300 return $response; }
The Request gathers what PHP scatters across $_GET, $_POST, $_COOKIE and $_SERVER: query, request, cookies, headers, files, with typed getters such as getInt() or getString(). The Response carries the status, the headers and the body; its variants, JsonResponse, RedirectResponse, BinaryFileResponse, StreamedResponse, cover the common cases, and its caching methods write Cache-Control, ETag or Last-Modified. The component also provides UriSigner, which signs a URL so nobody can tamper with it. The trap: a signed URL stays valid until it expires, even after it has been used. Without an expiration or a version, a password reset link found in a mailbox works a second time.
The exercises focus on what's new in Symfony 8.2: a reset link that only works once, a secret rotation that doesn't break links already sent, and a Cache-Control for the CDN that differs from the browser's.
3 exercises work on this concept, by writing code in the browser.
In Practice
- Change a secret without breaking the links already sent The secret of framework.uri_signer accepts a list: the first one signs new links, all of them check the ones still around.
- One Cache-Control for the CDN, another for the browser $response->cacheControl('CDN') writes a CDN-Cache-Control header: the CDN, which you can purge, keeps the page for a long time; the browser doesn't.
- A reset link that only works once UriSigner::sign() accepts a “version”: sign the link with the password hash, and it dies as soon as the password changes.