code4nix / uri-signer
支持过期选项的URI签名器
1.0.6
2024-02-07 19:03 UTC
Requires
- php: ^8.2
- symfony/http-foundation: >5.0
- symfony/http-kernel: >5.0
README
创建并检查支持过期时间的签名URI。此包是对Symfony的URI签名器的进一步开发。
安装
composer require code4nix/uri-signer
使用方法
创建签名URI
要创建一个过期时间为1天(默认值)的签名URI,您可以使用$this->uriSigner->sign($strUri)
。您可以通过添加第二个参数$intExpires
来添加自定义过期时间。例如,调用$this->uriSigner->sign($strUri, 600)
以获取过期时间为10分钟的URI。
检查签名URI/请求
要检查URI,您可以使用$this->uriSigner->check($strUri)
。
而不是构建URI,您还可以调用$this->uriSigner->checkRequest($request)
方法,并将一个Symfony\Component\HttpFoundation\Request
对象传递给该方法来检查相关URI的签名。这两个方法在URI通过验证时返回布尔值true
,如果URI无效或已过期,则返回布尔值false
。
错误处理
或者,您可以通过添加第二个可选的布尔参数以运行check()
或checkRequest()
方法,例如$this->uriSigner->check($strUri, true)
或$this->uriSigner->checkRequest($request, true)
,如果无法验证URI(例如,已被篡改、已过期或格式不正确),则会抛出异常。
MalformedUriException
InvalidSignatureException
ExpiredLinkException
在您的控制器中使用
<?php declare(strict_types=1); namespace App\Controller; use Code4Nix\UriSigner\Exception\ExpiredLinkException; use Code4Nix\UriSigner\Exception\InvalidSignatureException; use Code4Nix\UriSigner\Exception\MalformedUriException; use Code4Nix\UriSigner\UriSigner; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/uri_signer_test", name="uri_signer_test") */ class UriSignerTestController extends AbstractController { public function __construct( private readonly UriSigner $uriSigner, ) { } public function __invoke(Request $request): Response { // Sign a URI with an expiration time of 10 min $uri = 'https://foo.bar/test'; //https://foo.bar/test?_hash=eyJoYXNoZWQiOiJqNXUxeE1NRnpTRU1yRnREc $signedUri = $this->uriSigner->sign($uri, 600); // For test usage we will create our request object manually. $request = Request::create( $signedUri, ); $responseText = 'URI is valid.'; // Use check($signedUri, true) or checkRequest($request, true) // If set to true the second boolean parameter will raise exceptions if a URI cannot be verified. try { $this->uriSigner->checkRequest($request, true); // or $this->uriSigner->check($signedUri, true); } catch (MalformedUriException $e) { $responseText = 'Malformed URI detected!'; } catch (ExpiredLinkException $e) { $responseText = 'URI has expired!'; } catch (InvalidSignatureException $e) { $responseText = 'Invalid signature detected! The URI could have been tampered.'; } catch (\Exception $e) { $responseText = 'Oh, la, la! Something went wrong ;-('; } return new Response($responseText); } }
配置
默认过期时间和参数是可配置的
# config/config.yaml code4nix_uri_signer: parameter: '_signed' # default: '_hash' expiration: 20 # default: 86400 (1 day)