Out of the box, Laravel comes with the ability to generate “signed” URLs. These URLs have a hash in their query string that verifies that the URL was not modified.
At Flare, we use these signed URLs to add action links in mail notifications. The action links allow users to snooze and resolve errors right from the mail without having to be logged in. Pretty convenient!
My buddy Dries Vints noticed a slight drawback. He got a mail from Flare that contains these action links. A few hours after the mail arrived, he clicked one of the action links. This is what he saw.
This error screen is confusing: you might think that the links in the mail are invalid. To keep things secure, we use a short lifetime for our signed URLs. Dries got this screen because the link had expired.
We can improve on this by creating a dedicated error message when clicking expired or invalid links. Luckily, this is not that difficult.
When you try to validate a signed URL and the validation fails, Laravel will throw a dedicated exception IlluminateRoutingExceptionsInvalidSignatureException
In your exception handler, you can listen for that exception and render a dedicated view.
<span class="hljs-comment">// in app/Exceptions/Handler.php</span>
<p><span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span><span class="hljs-title">Routing<span class="hljs-title">Exceptions<span class="hljs-title">InvalidSignatureException;</p>
<p><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">render</span><span class="hljs-params">($request, Throwable $exception)</span>
</span>{
<span class="hljs-keyword">if</span> ($exception <span class="hljs-keyword">instanceof</span> InvalidSignatureException) {
<span class="hljs-keyword">return</span> response()->view(<span class="hljs-string">'errors.link-expired'</span>)->setStatusCode(Response::HTTP_FORBIDDEN);
}</p>
<pre><code><span class="hljs-comment">// ...</span>
}
With that code in place, this is what Dries will see when clicking another expired link in the future.
And that is all there is to it. To avoid confusions for your users, I highly recommend setting up a dedicated error message when using signed URLs.
Thanks for bringing this to my attention, Dries.