Skip to content

Instantly share code, notes, and snippets.

@reinink
Created March 7, 2018 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reinink/b42f6ddbac64eb0fd436762086e94805 to your computer and use it in GitHub Desktop.
Save reinink/b42f6ddbac64eb0fd436762086e94805 to your computer and use it in GitHub Desktop.
Signed routes in Laravel
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
// ...
protected $routeMiddleware = [
// ...
'signed' => \App\Http\Middleware\ValidateSignature::class,
];
}
<?php
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\Facades\Config;
UrlGenerator::macro('signedRoute', function ($route, $parameters) {
return $this->route($route, $parameters + [
's' => hash_hmac('sha256', $this->route($route, $parameters), Config::get('app.key')),
]);
});
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
class ValidateSignature
{
public function handle($request, Closure $next, $guard = null)
{
$originalUrl = $request->url().'?'.http_build_query(Arr::except($request->query(), 's'));
$signature = hash_hmac('sha256', $originalUrl, Config::get('app.key'));
if ($signature !== $request->get('s')) {
App::abort(401, 'Invalid signature');
}
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment