Laravel - URL Generation - Validating Signed Route Requests
To verify that an incoming request has a valid signature, you should call the hasValidSignature
method on the incoming Request
:
use Illuminate\Http\Request;
Route::get('/unsubscribe/{user}', function (Request $request) {
if (! $request->hasValidSignature()) {
abort(401);
}
// ...
})->name('unsubscribe');
Alternatively, you may assign the Illuminate\Routing\Middleware\ValidateSignature
middleware to the route. If it is not already present, you should assign this middleware a key in your HTTP kernel's routeMiddleware
array:
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
];
Once you have registered the middleware in your kernel, you may attach it to a route. If the incoming request does not have a valid signature, the middleware will automatically return a 403
HTTP response:
Route::post('/unsubscribe/{user}', function (Request $request) {
// ...
})->name('unsubscribe')->middleware('signed');