Skip to content

Commit 5ad3d99

Browse files
[HttpFoundation] add documention for signed URI expiration
1 parent d517b34 commit 5ad3d99

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

routing.rst

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2694,6 +2694,71 @@ service, which you can inject in your services or controllers::
26942694
}
26952695
}
26962696

2697+
You can make the signed URI expire. To do so, you can pass a value to the `$expiration` argument
2698+
of :phpmethod:`Symfony\\Component\\HttpFoundation\\UriSigner::sign`. This optional argument is `null` by default. You can
2699+
specify an expiration date by several ways::
2700+
2701+
// src/Service/SomeService.php
2702+
namespace App\Service;
2703+
2704+
use Symfony\Component\HttpFoundation\UriSigner;
2705+
2706+
class SomeService
2707+
{
2708+
public function __construct(
2709+
private UriSigner $uriSigner,
2710+
) {
2711+
}
2712+
2713+
public function someMethod(): void
2714+
{
2715+
// ...
2716+
2717+
// generate a URL yourself or get it somehow...
2718+
$url = 'https://example.com/foo/bar?sort=desc';
2719+
2720+
// sign the URL with an explicit expiration date
2721+
$signedUrl = $this->uriSigner->sign($url, new \DateTime('2050-01-01'));
2722+
// $signedUrl = 'https://example.com/foo/bar?sort=desc&_expiration=2524608000&_hash=e4a21b9'
2723+
2724+
// check the URL signature
2725+
$uriSignatureIsValid = $this->uriSigner->check($signedUrl);
2726+
// $uriSignatureIsValid = true
2727+
2728+
// if given a \DateInterval, it will be added from now to get the expiration date
2729+
$signedUrl = $this->uriSigner->sign($url, new \DateInterval('PT10S')); // Valid for 10 seconds from now
2730+
// $signedUrl = 'https://example.com/foo/bar?sort=desc&_expiration=1712414278&_hash=e4a21b9'
2731+
2732+
// check the URL signature
2733+
$uriSignatureIsValid = $this->uriSigner->check($signedUrl);
2734+
// $uriSignatureIsValid = true
2735+
2736+
sleep(30); // wait 30 seconds...
2737+
2738+
// the URL signature has expired
2739+
$uriSignatureIsValid = $this->uriSigner->check($signedUrl);
2740+
// $uriSignatureIsValid = false
2741+
2742+
// you can also use a timestamp in seconds
2743+
$signedUrl = $this->uriSigner->sign($url, 4070908800); // timestamp for the date 2099-01-01
2744+
// $signedUrl = 'https://example.com/foo/bar?sort=desc&_expiration=4070908800&_hash=e4a21b9'
2745+
2746+
}
2747+
}
2748+
2749+
.. caution::
2750+
2751+
`null` means no expiration for the signed URI.
2752+
2753+
.. note::
2754+
2755+
When making the URI expire, an `_expiration` query parameter is added to the URL and the expiration date is
2756+
converted into a timestamp
2757+
2758+
.. versionadded:: 7.1
2759+
2760+
The possibility to add an expiration date for a signed URI was introduced in Symfony 7.1.
2761+
26972762
Troubleshooting
26982763
---------------
26992764

0 commit comments

Comments
 (0)