承接 dsentker/url-signature-bundle 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

dsentker/url-signature-bundle

Composer 安装命令:

composer require dsentker/url-signature-bundle

包简介

A symfony 4 bundle for creating url signatures

README 文档

README

A Symfony >=4 bundle for the url-signature library.

This bundle allows you to build URLs with a signature in query string to prevent the modification of URL parts form a user. For a more detailed description, view the README from url-signature library .

Features:

  • URL generation in Twig Templates
  • URL generation and URL validation with a controller helper trait
  • URL generation and URL validation with Dependency Injection in your controllers
  • URL validation in your controller with Annotation

Installation

Use composer to install this bundle:

require dsentker/url-signature-bundle

If you use Symfony Flex, you do not have to do anything anymore. Otherwise you have to include the bundle in your <root>/config/bundles.php like this:

<?php
return [
    // ...
    Shift\UrlSignatureBundle\ShiftUrlSignatureBundle::class => ['all' => true],
];

Usage

Create signed URLs in your Twig Template

This bundle comes with a twig extension to create an url from any route name: signed_url() (and, as alias, signed_path()) works just like the symfony / twig function path() which you have certainly used a hundredfold. signed_path expects a route name as first argument and, optionally, query data as array:

<!-- Generating a link -->
<a href="{{ path('member_detail', { id: user.id }) }}">A Link </a>

<!-- A link with a hash signature -->
<a href="{{ signed_url('member_detail', { id: user.id }) }}">A Link with a signature</a>

Both links lead to the same target, but the link created via signed_url(...) has a hash in the query string. This hash can be validated in the destination controller.

To set an expiry date for a URL, pass the date as the 3rd parameter:

<a href="{{ signed_url('member_detail', { id: user.id }, '+10 minutes') }}">A Link with a signature, expires in 10 minutes</a>

The expiration value can be

  • a relative string (parsable with date() function )
  • a \DateTime object
  • a timestamp as integer

If the hash value is checked AFTER the expiration time, it is invalid.

Sign URLs in your controller

Use dependency injection to get an instance of Shift\UrlSignatureBundle\Utils\UrlSignatureBuilder:

use Shift\UrlSignatureBundle\Utils\UrlSignatureBuilder;

class ExampleController extends AbstractController
{
    /**
     * @Route("/member/detail/{id}", name="member_detail")
     */
    public function index(User $user, UrlSignatureBuilder $builder) {
        
        // Just like the Twig function, the UrlSignatureBuilder offers in the third 
        // parameter to set an expiration date.
        $hashedUrl = $builder->signUrlFromPath('example_path', ['param1' => 'value1'], '+10 minutes');
        
        // You can also create a signature for a regular URL (without referring to a route path)
        $hashedUrl = $builder->signUrl('https://example.com/foo', '+10 minutes');
        
    }

Verify URLs

This bundle offers several ways to check the signature of the URL in your controller.

Verify a signature with dependency injection (recommended)

Inject an Shift\UrlSignatureBundle\Utils\RequestValidator instance to your action:

use Shift\UrlSignatureBundle\Utils\RequestValidator;

class ExampleController extends AbstractController
{
    /**
     * @Route("/member/detail/{id}", name="member_detail")
     */
    public function index(User $user, RequestValidator $signatureValidator) {
        
        if(!$signatureValidator->isValid()) {
            // is Signature missing or invalid? Show an alert, redirect or do something you like    
        }

        // Alternatively, you can use this method. It throws an exception if the hash value
        // is missing or not valid.
        $signatureValidator->verify();

        // There is no need to also inject the request object to your 
        // action method as it is provided by RequestValidator instance.
        $request = $signatureValidator->getRequest();

    }

Verify a signature with an Annotation

Annotate your controller action like the following example:

use Shift\UrlSignatureBundle\Annotation\RequiresSignatureVerification;

class ExampleController extends AbstractController
{
    /**
     * @RequiresSignatureVerification()
     *
     * @Route("/member/detail/{id}", name="member_detail")
     */
    public function index(User $user) {
        // ...
    }
}

If the annotation is present, an Event Listener checks the incoming request URL. If the signature is missing (or invalid), an \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException is thrown before your action is called. Make sure to give the user an useful response if an AccessDeniedException is thrown (This applies regardless of the use of this bundle, of course).

Build hashed URLs and verify signatures with a trait

This bundle comes with a trait to make the access to the Builder and RequestValidator easier::

use Shift\UrlSignatureBundle\Controller\UrlSignatureTrait;

class SingleActionController extends AbstractController
{
    
    use UrlSignatureTrait;

    /**
     * @Route("/member/detail/{id}", name="member_detail")
     */
    public function index(User $user) {

        /** @var Shift\UrlSignatureBundle\Utils\UrlSignatureBuilder $builder */
        $builder = $this->getBuilder();
        
        /** @var Shift\UrlSignatureBundle\Utils\RequestValidator $validator */
        $validator = $this->getValidator();

    }
}

Note: The trait has its own constructor. If your controller already has a constructor, you should not use this trait. Read more at StackOverflow about "constructor in traits".

Advanced Usage

Customize the configuration

Configuration is already done with the help of the Service Container. To create a signature, a secret is needed. By configuration, this secret is equivalent to the value of your APP_SECRET from the .env file in your project root.

As you know, you can override parameters and dependencies in your config/services.yaml. Here is an example:

parameters:
    shift_url_signature.hash_algo: 'MD5'
    shift_url_signature.query_signature_name: '_hash'

Look at the service container configuration file in this repository to see what you want to adjust.

Here is an complete example for the configuration of the hash configuration:

shift_url_signature.configuration.default:
        class:  UrlSignature\HashConfiguration
        shared: true
        arguments: ['%shift_url_signature.secret%']
        calls:
            -   method: setAlgorithm
                arguments:
                    - '%shift_url_signature.hash_algo%'
            -   method: setHashMask
                arguments:
                    - !php/const UrlSignature\HashConfiguration::FLAG_HASH_SCHEME
                    - !php/const UrlSignature\HashConfiguration::FLAG_HASH_HOST
                    - !php/const UrlSignature\HashConfiguration::FLAG_HASH_PORT
                    - !php/const UrlSignature\HashConfiguration::FLAG_HASH_PATH
                    - !php/const UrlSignature\HashConfiguration::FLAG_HASH_QUERY
            -   method: setSignatureUrlKey
                arguments: ['%shift_url_signature.query_signature_name%']
            -   method: setTimeoutUrlKey
                arguments: ['%shift_url_signature.query_expires_name%']

Do not be surprised at the weird looking arguments for the setHashMask method - I did not find a better solution to set a bitmask in a services.yaml.

Submitting bugs and feature requests

Bugs and feature request are tracked on GitHub.

TODO

  • Create more tests. I look forward to every support.
  • Restructure this bundle for the new directory structure coming with Symfony >= 5.0

Testing

./vendor/bin/phpunit Shift/UrlSignatureBundle/Tests/

Or, if you use Windows:

 .\vendor\bin\phpunit.bat Shift/UrlSignatureBundle/Tests/ --configuration phpunit.xml

dsentker/url-signature-bundle 适用场景与选型建议

dsentker/url-signature-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 37.64k 次下载、GitHub Stars 达 9, 最近一次更新时间为 2019 年 03 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「symfony」 「build」 「bundle」 「uri」 「signature」 「validate」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 dsentker/url-signature-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 dsentker/url-signature-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 dsentker/url-signature-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 37.64k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 9
  • 点击次数: 14
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 9
  • Watchers: 3
  • Forks: 5
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-03-06