Symfony:如何自动加密/解密路由参数?

时间:2015-11-05 11:04:22

标签: php symfony encryption

我想在网址/路线自动启用/解密参数 (例如ID),例如:

domain.com/item/show/1应该看起来像domain.com/item/show/uj7hs2

当前(伪)代码

public function myControllerFunctionAction() {
    // ...
    $id = $this->get('my.crypt')->encrypt($item->getId());
    return $this->redirectToRoute('routeTo_myOtherControllerAction', array('id' => $id));
}

public function myOtherControllerFunctionAction($id) {
    $id = $this->get('my.crypt')->decrypt($id); // decrypt

    $item = $this->get('my.repository')->find($id);
    // ...
}

我想避免手动加密/解密

这样的事情会很完美:

# routing.yml
routeTo_myOtherControllerAction:
    path:     /item/show/{id}
    defaults: { _controller: appBundle:Items:show }
    options:
        crypt_auto: true
        crypt_method: %default_crypt_method%

我找不到任何其他解决方案,而不是我的服务。有什么想法吗?

提前致谢!

2 个答案:

答案 0 :(得分:6)

所以,只是为了澄清:

  1. 您想混淆数据库记录ID(即主键)?
  2. 您希望生成的网址缩短。
  3. 如果您回答"是"对于这两个问题,请考虑遵循此guide to URL parameter encryption

    人们想做什么

    Some encryption function is used to deterministically retrieve the ID

    人们应该做什么

    Use a separate column

    如果我的网址较长,该怎么办?

    使用defuse/php-encryption。它提供authenticated encryption,是可用性最好的PHP加密库之一。 (它也被允许许可。)

    if (isChecked)

答案 1 :(得分:3)

您可以使用NzoUrlEncryptorBundle这样做,这也是我出于同样的原因使用的。我只是在下面给出了参考其自述文件的示例。您可以查看它以获取更多详细信息。

功能包括:

  • 网址数据&参数加密
  • 网址数据&参数解密
  • 数据加密&解密
  • 轻松访问Twig
  • 灵活配置

<强>的routing.yml

my-path-in-the-routing:
    path: /my-url/{id}
    defaults: {_controller: MyBundle:MyController:MyFunction}

在带注释服务的控制器中

use Nzo\UrlEncryptorBundle\Annotations\ParamDecryptor;
//...

    /**
     * @ParamDecryptor(params="id, toto, bar")
     */
     public function indexAction(User $id, $toto) 
    {
        // no need to use the decryption service here as the parameters are already decrypted by the annotation service.
        //....

    }

在没有注释服务的控制器中:

public function indexAction($id) 
{
    $MyId = $this->get('nzo_url_encryptor')->decrypt($id);

    //....

}

 public function indexAction() 
{   
    //....

    $Encrypted = $this->get('nzo_url_encryptor')->encrypt($data);

    //....

}