如何在 Laravel 5.4 中的参数位置创建 url 签名

问题描述 投票:0回答:1

这只是我的想法,我只想做同样的事情,我没有尝试过这个,因为我不知道这意味着它将如何完成。

例如:

我有 -

mysite.com/view?user_id=12
,我不想在url上显示url的参数(
?user_id=12
),在这个地方,我想显示像

mysite.com/view?_signature=encryptedparameter 

(如:

mysite.com/view?_signature=853ef7a0ff5aea6f24152b1d1ed4d771

853ef7a0ff5aea6f24152b1d1ed4d771
将表示
user_id=12

如果我有多个参数,它会是一样的,我将有一个加密字符串,我将获得该字符串的所有参数。

php laravel-5 encryption domain-masking
1个回答
1
投票

是的,但我在 Laravel 5.1 中使用

假设我有“mysite.com/view?user_id=12”

我想要“mysite.com/view?_signature=encryptedparameter”

请遵循一些步骤

laravel>packages>myfolder>core


+=>folder
-=>file     

+packages
    +Folder
        +core
            +src
                +Faundation
                    -Application.php
                +Routing
                    -RoutingServiceProvider.php
                    -UriGenerator.php   
                +Support
                    +Middleware
                        -UrlParamRevealerMiddleware.php
                    +ServiceProvider
                        -CoreServiceProvider.php
                    -UriParamProtector.php

                    

<<IN APPLICATION.PHP>>

<?php

namespace Folder\Core\Foundation;

use Illuminate\Events\EventServiceProvider;
use Folder\Core\Routing\RoutingServiceProvider;
use Illuminate\Foundation\Application as BaseApplication;
use Folder\Core\Support\ServiceProvider\CoreServiceProvider;

class Application extends BaseApplication
{
    /**
     * Register all of the base service providers.
     *
     * @return void
     */
    protected function registerBaseServiceProviders()
    {
        $this->register(new EventServiceProvider($this));

        $this->register(new CoreServiceProvider($this));

        $this->register(new RoutingServiceProvider($this));
    }
}
<<//IN APPLICATION.PHP>>


<<-RoutingServiceProvider>>

<?php

namespace Folder\Core\Routing;

use Folder\Core\Routing\UrlGenerator;
use Illuminate\Routing\RoutingServiceProvider as BaseServiceProvider;

class RoutingServiceProvider extends BaseServiceProvider
{

    /**
     * Register the URL generator service.
     *
     * @return void
     */
    protected function registerUrlGenerator()
    {
        $this->app['url'] = $this->app->share(function ($app) {
            $routes = $app['router']->getRoutes();

            // The URL generator needs the route collection that exists on the router.
            // Keep in mind this is an object, so we're passing by references here
            // and all the registered routes will be available to the generator.
            $app->instance('routes', $routes);

            $url = $this->getUrlGenerator($routes);

            $url->setSessionResolver(function () {
                return $this->app['session'];
            });

            // If the route collection is "rebound", for example, when the routes stay
            // cached for the application, we will need to rebind the routes on the
            // URL generator instance so it has the latest version of the routes.
            $app->rebinding('routes', function ($app, $routes) {
                $app['url']->setRoutes($routes);
            });

            return $url;
        });
    }

    /**
     * Get the url generator instance.
     *
     * @param \Illuminate\Routing\RouteCollection $routes
     * @return \Folder\Core\Routing\UrlGenerator
     */
    protected function getUrlGenerator($routes)
    {
        $url = new UrlGenerator(
            $routes,
            $this->app->rebinding(
                'request',
                $this->requestRebinder()
            )
        );

        return $url;
    }
}
<</-RoutingServiceProvider>>

<<UriGenerator.php>>
<?php

namespace Folder\Core\Routing;

use ErrorException;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Routing\UrlGenerator as BaseUrlGenerator;

class UrlGenerator extends BaseUrlGenerator
{

    /**
     * Get the URL to a named route.
     *
     * @param  string  $name
     * @param  mixed   $parameters
     * @param  bool  $absolute
     * @return string
     *
     * @throws \InvalidArgumentException
     */
    public function route($name, $parameters = [], $absolute = true)
    {
        $encryptedParameters = $parameters;

        if (Auth::guest() === false) {
            $encryptedParameters = $this->encrypt($name, $parameters);
        }

        return parent::route($name, $encryptedParameters, $absolute);
    }

    /**
     * Get the cryptic engine.
     *
     * @return \Folder\Core\Support\UrlParamEncrypter
     *
     * @throws \ErrorException
     */
    protected function getCrypt()
    {
        $app = App::getInstance();

        if (isset($app['urlencryptor'])) {
            return $app['urlencryptor'];
        }

        throw new ErrorException('URL Encryptor was not found.');
    }

    /**
     * Get the protector engine.
     *
     * @return @return \Folder\Core\Support\UrlParamProtector
     *
     * @throws \ErrorException
     */
    protected function getProtector()
    {
        $app = App::getInstance();

        if (isset($app['urlprotector'])) {
            return $app['urlprotector'];
        }

        throw new ErrorException('URL Protector was not found.');
    }

    /**
     * Encrypts the parameter passed as querystring in URL.
     *
     * @param array $parameters
     * @return array
     */
    protected function encrypt($routeName, $parameters = [])
    {

        if (! is_array($parameters)) {
            return $parameters;
        }
        
        if (count($parameters) === 0) {
            return [];
        }

        if (Auth::guest() === true) {
            return $parameters;
        }

        $protected = $this->getProtector()->protect($routeName, $parameters);

        return ['__signature' => $protected];
    }
}

<<//UriGenerator.php>>

<<UrlParamRevealerMiddleware.php>>
<?php

namespace Folder\Core\Support\Middleware;

use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Folder\Core\Support\UrlParamProtector;

class UrlParamRevealerMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        (! Auth::guest()) && App::make(UrlParamProtector::class)->reveal($request);
        
        return $next($request);
    }
}

<<//UrlParamRevealerMiddleware.php>>

<<CoreServiceProvider.php>>
<?php

namespace Folder\Core\Support\ServiceProvider;

use Illuminate\Support\ServiceProvider;
use Folder\Core\Support\UrlParamProtector;

class CoreServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->app->make('Illuminate\Contracts\Http\Kernel')
            ->pushMiddleware('Folder\Core\Support\Middleware\UrlParamRevealerMiddleware');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerUrlProtector();
    }

    /**
     * Register UrlProtector class.
     */
    protected function registerUrlProtector()
    {
        $this->app->singleton('urlprotector', function () {
            return new UrlParamProtector();
        });
    }
}

<<//CoreServiceProvider.php>>

<<-UriParamProtector.php>>
<?php

namespace Folder\Core\Support;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class UrlParamProtector
{

    /**
     * Session key.
     *
     * @var string
     */
    protected $sessionKey = '__url_protector__';

    /**
     * Request class.
     *
     * @var \Illuminate\Http\Request
     */
    protected $request;

    /**
     * Values those needs to be merged in request object.
     *
     * @var array
     */
    protected $valuesToBeMerged;

    /**
     * Create and returns VALID RFC 4211 COMPLIANT
     * Universally Unique IDentifiers (UUID) version 4.
     *
     * @return string
     */
    protected function getNewGuid()
    {
        if (function_exists('com_create_guid') === true) {
            return trim(com_create_guid(), '{}');
        }

        return sprintf(
            '%04X%04X-%04X-%04X-%04X-%04X%04X%04X',
            mt_rand(0, 65535),
            mt_rand(0, 65535),
            mt_rand(0, 65535),
            mt_rand(16384, 20479),
            mt_rand(32768, 49151),
            mt_rand(0, 65535),
            mt_rand(0, 65535),
            mt_rand(0, 65535)
        );
    }

    /**
     * Create the route key.
     *
     * @param string $routeName
     * @param array $parameters
     * @return string
     */
    protected function getRouteKey($routeName, array $parameters = [])
    {
        if (count($parameters) <= 0) {
            $paramToString = '';
        } else {
            $paramToString = implode('-', array_map(
                function ($k, $v) {
                        return $k . '-' . $v;
                },
                array_keys($parameters),
                array_values($parameters)
            ));
        }

        $routeKey = 'route__' . $routeName . (empty($paramToString) ? '' : '-' . $paramToString);

        return $routeKey;
    }

    /**
     * Returns a GUID for a URL parameter.
     *
     * @param string $routeName
     * @param array $parameters
     * @return string
     */
    public function protect($routeName, array $parameters)
    {
        $routeKey = $this->getRouteKey($routeName, $parameters);

        if (Session::has($this->sessionKey . '.' . $routeKey) === false) {
            $guid = Str::lower($this->getNewGuid());

            Session::set($this->sessionKey . '.' . $routeKey, [
                'guid' => $guid,
                'loggedin_user_id' => (Auth::guest() ? 0 : Auth::user()->id),
                'params' => $parameters,
            ]);
        } else {
            $guid = Session::get($this->sessionKey . '.' . $routeKey . '.guid');
        }

        return $guid;
    }

    /**
     * Check whether guid passed is a valid one or not.
     *
     * @param string $guid
     * @return boolean
     */
    protected function isValidGuid($guid)
    {
        foreach (Session::get($this->sessionKey) as $key => $value) {
            if (!isset($value['guid'])) {
                list($innerKey, $val) = each($value);
            } else {
                $val = $value;
            }
            if ($val['guid'] === $guid) {
                $this->valuesToBeMerged = $val['params'];
                return true;
            }
        }

        return false;
    }

    /**
     * Check whether guid passed is a valid one or not.
     *
     * @param string $guid
     * @return boolean
     */
    public function isValidGuidForPost($guid)
    {
        foreach (Session::get($this->sessionKey) as $key => $value) {
            if ($value['guid'] === $guid && Auth::user()->id === $value['loggedin_user_id']) {
                $this->valuesToBeMerged = $value['params'];
                return true;
            }
        }

        return false;
    }

    /**
     * Merge the request with our revealed values.
     */
    protected function mergeRequest()
    {
        $this->request->merge($this->valuesToBeMerged);
    }

    /**
     * Check whether a "__signature" is correct or not.
     *
     * @param \Illuminate\Http\Request $request
     * @return boolean
     */
    public function reveal(Request &$request)
    {
        $this->request = $request;

        $guid = ($this->request->query('__signature') ? : false);

        if ($guid === false) {
            return false;
        }

        if ($this->isValidGuid($guid) === false) {
            App::abort(400);
        }

        $this->mergeRequest();
    }
}


<<//-UriParamProtector.php>>

================================================ 之后,在“bootstrap>App.php”中使用这个:

$app = new Folder\Core\Foundation\Application(
    realpath(__DIR__.'/../')
);

而不是:

$app = new Illuminate\Foundation\Application(
   realpath(__DIR__.'/../')
);

在任何链接中使用“data-href”:

<a data-href="route('modify_lead_status',['user_id' => $users->id])" href="javascript:void(0)"><i class=\"fa fa-random\"></i></a>"
                

之后任何控制器、路由、中间件都将是相同的...

composer auto-dump

<>

© www.soinside.com 2019 - 2024. All rights reserved.