Search code examples
phplaravelquery-stringlaravel-5.7whitelist

Laravel 5.7: Where can I register the allowed GET parameters and block others?


I have simple Laravel application and I have custom allowed GET parameters for my app:

$allowedGetParameters = [
  'user',
  'event',
  'action'
]

How can I block all other GET parameters except the specified parameters in the array?

For example possible URL addresses:

 - https://app.com/?user=16
 - https://app.com/?event=242&user=16
 - https://app.com/?user=16&event=242&action=like

URL with other GET parameters must return response 404. Here example URLs:

 - https://app.com/?user=16&post=43&like=true
 - https://app.com/?guru=242&set=superguru&action=true

Note:

If the URLs contain one or more unallowed GET parameters with or without allowed GET parameters in this case, the result should also be returned 404.


Solution

  • Create middleware https://laravel.com/docs/5.7/middleware

    implement handle method, where you are make your checks:

    $params = array_keys($request->all());
    $is_valid_params = count(array_diff($params, $allowedGetParameters)) == 0;
    $is_get_request = $request->method() == 'GET';
    if ($is_valid_params && $is_get_request) {
        return $next($request);
    };
    return abort(404);
    

    Also I would move $allowedGetParameters to config folder in somefile.php, and would access like that: count(array_diff($params, config('somefile.allowedGetParameters')) == 0;

    Don't forget to:

    1) register your middleware in app\Http\Kernel.php in protected $routeMiddleware

    2) wrap your routes in web.php with:

    Route::group(['middleware' => ['name_of_your_widdleware']], function () {