12
JanLaravel URL Signer is a package by Spatie that can create and validate secured signed URLs with a limited lifetime in Laravel. This is done by adding an expiration date and a signature to the URL.
This is how you can create a signed URL that’s valid for 30 days:
UrlSigner::sign('https://myapp.com/protected-route', 30);
The output will look like this:
https://app.com/protected-route?expires=xxxxxx&signature=xxxxxx
The URL can be validated with the validate
function.
UrlSigner::validate('https://app.com/protected-route?expires=xxxxxx&signature=xxxxxx');
The package also provides a middleware to protect routes.
As you would have guessed the package can be installed via Composer:
composer require spatie/laravel-url-signer
The configuration file can optionally be published via:
php artisan vendor:publish --provider="Spatie\UrlSigner\Laravel\UrlSignerServiceProvider"
Signing URLs
URL’s can be signed with the sign
method:
UrlSigner::sign('https://myapp.com/protected-route');
By default, the lifetime of an URL is one day. This value can be changed in the config-file
. If you want a custom lifetime, you can specify the number of days the URL should be valid:
//the generated URL will be valid for 5 days.
UrlSigner::sign('https://myapp.com/protected-route', 5);
For fine-grained
control, you may also pass a DateTime
instance as the second parameter. The URL will be valid up to that moment. This example uses Carbon for convenience:
//This URL will be valid up until 2 hours from the moment it was generated.
UrlSigner::sign('https://myapp.com/protected-route', Carbon\Carbon::now()->addHours(2) );
Validating URLs
To validate a signed URL, simply call the validate()
method. This return a boolean
.
UrlSigner::validate('https://app.com/protected-route?expires=xxxxxx&signature=xxxxxx');
Protecting routes with middleware
The package also provides a middleware to protect routes:
Route::get('protected-route', ['middleware' => 'signedurl', function () {
return 'Hello secret world!';
}]);
Your app will abort with a 403 status code if the route is called without a valid signature.
If you want to dig more about this package you can visit its documentation and source code on Github.
Published at : 12-01-2022
I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.
Launch project