How to encrypt laravel 5.2 url or routes?

Do I need to encrypt routes in this url? Because I do not want the user to access the URL by changing the identifier of the element. For example, a user may change / items / 1234 to / item / 5678. Although elements 1234 and 5678 belong to the same user, I still want to limit the behavior. What I'm trying to do is route encryption, but I'm not sure if this is correct or not. Any suggestions?

+4
source share
6 answers

You can encrypt your url parameter and decrypt it in your controller. You can try the following:

In your view: suppose your parameter has an identifier or more parameter that you can encrypt.

<?php
        $parameter =[
            'id' =>1,
        ];
    $parameter= Crypt::encrypt($parameter);
?>
<a href="{{url('/url/',$parameter)}}" target="_blank">a link</a>

Your route will be:

Route::get('/url/{parameter}', 'YourController@methodName');

In your controller, you can decrypt your parameter:

public function methodName($id){
    $data = Crypt::decrypt($id);
  }

You must be the Crypt namespace at the top of the controller

use Illuminate\Support\Facades\Crypt;

Note. You can encrypt url parameter with Crypt::encrypt($parameter)and decrypt withCrypt::decrypt($parameter)

+5
source

You can encrypt the route in your controller when redirecting using

\Crypt::encrypt(product_id)

and on the product page, you can decrypt the product identifier from the URL using

$product_id = \Crypt::decrypt($url_parameter)

which is the best way.

But there will be some chances of an exception if the user changes the product identifier parameter from the URL that you need to handle.

+3
source

- (UUID).

URL- .

, ,

$table->increments('id');

:

$table->uuid('id')->primary();

, :

protected $incrementing = false;
+2

, . encrypt() decrypt() .

$encryptedId = encrypt($id);

https://laravel.com/docs/5.3/encryption#using-the-encrypter

+1

URL-/ URL, id. hashids library. , 347 yr8 .

:

composer require hashids/hashids

id Laravel 5

URL-:

http://example.com/users/123

http://example.com/users/Mj3

, !

0

, . , , . , . - .

  • , "/{encrypted}" @( ).

  • . , - "item/100". $routeParams = explode('/', $decrypted); .

if($routeParams[0] == 'item') { return ItemService::get($routeParams[1]); }

This is the main idea. But in practice, you will have a handler class that controls the routing of your encrypted URL. In this handler class, you will need to have a configuration array that will work similar to the Laravel routes file.

0
source

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


All Articles