Symfony: How to automatically encrypt / decrypt route parameters?

I would like to include / decrypt the parameters (e.g. ID) in the URL / route automatically , for example:

domain.com/item/show/1 should look like domain.com/item/show/uj7hs2 .

Current (pseudo) code

 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); // ... } 

I would like to avoid manual en / decrypting .

Something like this would be perfect:

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

I have not yet found a solution other than my service. Any ideas?

Thanks in advance!

+5
source share
2 answers

So, just to clarify:

  • Do you want to obfuscate the database record identifier (i.e. primary key)?
  • You want the resulting URL to be short.

If you answered yes to both of these questions, consider the following URL parameter encryption guide .

What do people want to do

Some encryption function is used to deterministically extract the identifier

What should people do instead

Use a separate column

What if i have longer urls?

Use defuse / php-encryption . It provides authenticated encryption and is one of the best-studied PHP encryption libraries. (This is also licensed.)

 $decrypted = Crypto::decrypt($urlParameter, $yourKey); // ... snip ... // echo "<a href=\"/your/url/?".http_build_query([ 'id' => Crypto::encrypt($yourRowId, $yourKey) ])."\">"; 
+5
source

You can do this with the NzoUrlEncryptorBundle , which I used for the same reason. I just give you examples below, referring to its readme file. You can look at it in more detail.

Features include:

  • Url Data and Settings Encryption
  • Url Data and parameters Decryption
  • Data Encryption and Decryption
  • Access with Twig is easy.
  • Flexible configuration

routing.yml

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

In the controller with the annotation service

 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. //.... } 

In a controller without an 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); //.... } 
+1
source

Source: https://habr.com/ru/post/1235290/


All Articles