New in Symfony 8.2 (in development). Controller attributes such as #[IsSignatureValid], #[IsCsrfTokenValid], #[Lock] or #[RateLimit] check the request before the controller, and throw an exception when it doesn't pass. Until now, there was no way to answer anything but an error page: for an expired confirmation link, you had to remove the attribute and redo the check by hand.
Before
#[Route('/confirm', name: 'confirm')] public function confirm(Request $request, UriSigner $signer): Response { try { $signer->verify($request); } catch (ExpiredSignedUriException) { return $this->redirectToRoute('link_expired'); } // ... }
Since Symfony 8.2
Keep the attribute, and add a nullable argument typed with the attribute's exception to the controller. If the check fails, Symfony passes the exception to it and calls the controller anyway; if it succeeds, the argument is null.
#[Route('/confirm', name: 'confirm')] #[IsSignatureValid] public function confirm(?ExpiredSignedUriException $linkExpired = null): Response { if (null !== $linkExpired) { return $this->redirectToRoute('link_expired'); } // ... }
| Attribute | Recoverable exception |
|---|---|
#[IsSignatureValid] |
SignedUriException (and its subclasses) |
#[IsCsrfTokenValid] |
InvalidCsrfTokenException |
#[Lock] |
LockConflictedException |
#[RateLimit] |
RateLimitExceededException |
Two rules to keep in mind: the controller always runs when a failure is passed to it, so it must look at the argument before doing anything; and #[IsGranted] never passes its failures, so that an oversight can't let a forbidden action through.
Your task
ConfirmationController sends a confirmation link valid for one hour (the “Sign up” request in the “Requests” tab produces one). Once the hour has passed, the link lands on a 403 page.
- When the link has expired, redirect to the
link_expiredpage, with the address, without confirming anything. - A tampered link hasn't expired, it's forged: it must still answer 404.