New in Symfony 5.1: Improved UriSigner
March 18, 2020 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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)) {
// ...
}
}
}
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.