New in Symfony 5.1: Improved UriSigner

Contributed by
Yanick Witschi
in #35284 and #35298.

In Symfony applications, the service related to the UriSigner class adds a signature to URLs to prevent their manipulation. Symfony uses it for example to sign the URLs generated when using fragments in features such as ESI.

In Symfony 5.1 we've improved the UriSigner class with a new method called checkRequest(). This allows to pass a Symfony\Component\HttpFoundation\Request object to check the signature of its related URL, instead of having to build the URL yourself:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Before
$url = $request->getSchemeAndHttpHost()
    .$request->getBaseUrl()
    .$request->getPathInfo()
    .(null !== ($qs = $request->server->get('QUERY_STRING')) ? '?'.$qs : '');

if ($this->signer->check($url)) {
    // ...
}

// After
if ($this->signer->checkRequest($request)) {
    // ...
}

Another improvement introduced in Symfony 5.1 is that you can now autowire the uri_signer service. Instead of injecting that service manually, type-hint any argument of your services or controllers with the Symfony\Component\HttpKernel\UriSigner class to get the service:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\UriSigner;

class MyController extends AbstractController
{
    public function someMethod(Request $request, UriSigner $uriSigner)
    {
        if (!$uriSigner->checkRequest($request)) {
            // ...
        }
    }
}

Comments

Minor correction: In both if statements of the first code block the closing parentesis of the condition is missing.
@Laszlo good catch! Fixed. Thanks.

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.