Git Product home page Git Product logo

laravel-url-signer's Introduction

Create signed URLs with a limited lifetime in Laravel

Latest Version on Packagist Build Status Quality Score Total Downloads

This package can create URLs with a limited lifetime. This is done by adding an expiration date and a signature to the URL.

The difference with Laravel's native route signing is that using this package:

  • you can easily use signed URLs between different apps
  • the signing secret used is not tied to the app key
  • you can easily sign any URL (and not only a route belonging to your app)

This is how you can create signed URL that's valid for 30 days:

use Spatie\UrlSigner\Laravel\Facades\UrlSigner;

UrlSigner::sign('https://myapp.com/protected-route', now()->addDays(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.

// returns `true` if the signed URL is valid, `false` if not
UrlSigner::validate('https://app.com/protected-route?expires=xxxxxx&signature=xxxxxx');

The package also provides a middleware to protect routes.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

As you would have guessed the package can be installed via composer:

composer require spatie/laravel-url-signer

You must set an environment variable called URL_SIGNER_SIGNATURE_KEY and set it to a long secret value. This value will be used to sign and validate signed URLs.

# in your .env file

URL_SIGNER_SIGNATURE_KEY=some_random_value

The configuration file can optionally be published via:

php artisan vendor:publish --tag="url-signer-config"

This is the content of the file:

return [
    /*
    * This string is used the to generate a signature. You should
    * keep this value secret.
    */
    'signature_key' => env('URL_SIGNER_SIGNATURE_KEY'),

    /*
     * The default expiration time of a URL in seconds.
     */
    'default_expiration_time_in_seconds' => 60 * 60 * 24,

    /*
     * These strings are used a parameter names in a signed url.
     */
    'parameters' => [
        'expires' => 'expires',
        'signature' => 'signature',
    ],
];

Usage

URL's can be signed with the sign-method:

use Spatie\UrlSigner\Laravel\Facades\UrlSigner;

UrlSigner::sign('https://myapp.com/protected-route');

By default, the lifetime of an URL is one day. This value can be change in the config file. If you want a custom lifetime, you can specify the number of days the URL should be valid:

use Spatie\UrlSigner\Laravel\Facades\UrlSigner;

// the generated URL will be valid for 5 minutes.
UrlSigner::sign('https://myapp.com/protected-route', now()->addMinutes(5));

// alternatively you could also pass the amount of seconds
UrlSigner::sign('https://myapp.com/protected-route', 60 * 5);

Validating URLs

To validate a signed URL, simply call the validate()-method. This method returns a boolean.

use Spatie\UrlSigner\Laravel\Facades\UrlSigner;

UrlSigner::validate('https://app.com/protected-route?expires=xxxxxx&signature=xxxxxx');

Protecting routes with middleware

The package provides a middleware to protect routes.

To use it you must first register the Spatie\UrlSigner\Laravel\Middleware\ValidateSignature as route middleware in your HTTP kernel.

// in app/Http/Kernel.php

protected $routeMiddleware = [
    // ...
    'signed-url' => \Spatie\UrlSigner\Laravel\Middleware\ValidateSignature::class,
];

Next, you can apply it on any route you want.

Route::get('protected-route', fn () => 'Hello secret world!')
    ->middleware('signed-url');

Your app will abort with a 403 status code if the route is called without a valid signature.

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

You can run the test using this command:

composer test

Usage outside Laravel

If you're working on a non-Laravel project, you can use the framework agnostic version.

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-url-signer's People

Contributors

adriaanzon avatar adrianmrn avatar akoepcke avatar d13r avatar dependabot[bot] avatar freekmurze avatar jbrooksuk avatar jeff-h avatar laravel-shift avatar leonhh avatar omranic avatar sebastiandedeyne avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-url-signer's Issues

Dependency has problem

The dependency named league/url is not supported after few days and has been abandoned

so i think we should use league/uri instead, isn't it?

Do you have time or I should send PR?

Fatal error in UrlSigner

Hi, I'm still learning how to use Laravel, so it's possible I've got something wrong.

I've followed the installation and configuration instructions, and I've been over them several times to check that everything is correct.

In: app/Http/Controllers/VenuesManageController.php I have:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Exceptions\Handler;

use UrlSigner;

use App\Venues;

class VenuesManageController extends Controller
{

	public function get_url()
	{
		echo UrlSigner::sign('https://myapp.com/user/1/unsubscribe', 1);
	}

}

But I get an error:

FatalErrorException

syntax error, unexpected ':', expecting ';' or '{'
in UrlSigner.php (line 17)

What's wrong?

Package league/url is abandoned

Dear Spatie,

We are using your nice URL signer package!
But everytime i perform a composer update it returns that the Package league/url is abandoned.
Just wanted to report this in case you guys are not aware of this.

Installing on Laravel 5.5 requirements fails

While I am trying to install in laravel 5.5 the requirements fails:

spatie/laravel-url-signer 2.3.0 requires illuminate/http ~5.8.0 -> satisfiable by illuminate/http[v5.8.0, v5.8.11, v5.8.12, v5.8.14, v5.8.15, v5.8.17, v5.8.18, v5.8.19, v5.8.2, v5.8.20, v5.8.22, v5.8.24, v5.8.27, v5.8.28, v5.8.29, v5.8.3, v5.8.30, v5.8.31, v5.8.4, v5.8.8, v5.8.9].

but I suppose the package should be available up to Laravel 5.6

Signed URLs throwing 403 error with additional parameters.

Hello, I just used your signed url package and it is working fine with normal urls but a url with additional parameters is generating 403 error. I'm using Laravel 5.4 and my code is as follows:

//This is my Route
Route::get('/get-user', ['middleware' => 'signedurl', 'uses' => 'HomeController@getUser']);

//This is my function
public function getUser(Request $request)
{
print_r($request->all());
}

//This is my url generated by this package
http://localhost/MYPROJECT/get-user?expires=1557553652&signature=0bd90275ad12f422dc13b167cb75a829&zip=90038&isTomorrow=1&timeslot=d86c1db3-96ae-497d-bc96-2426adg4g43

If I run above generated url in browser, it will throw 403 error but if I'll run this url only with expires and signature, it will work fine. I want signed url working with additional parameters. Please help me out! Thanks in advance.. :-)

Invalidate url

Is it possible to make the URL invalid?

Thanks for reply.

Signing a URL with query string parameters may not validate correctly

I ran into an issue where I was signing a URL with several query string parameters. For example: https://www.example.com/posts?date_start=2019-01-01&date_end=2019-03-01 Note that the parameter order is date_start followed by date_end. The URL is signed without any issues but then in the ValidateSignature middleware it uses $request->fullUrl() to get the URL but the issue is that it will return the URL with the query string parameters sorted alphabetically which in this case would be a URL like https://example.com/posts?date_end=2019-03-01&date_start=2019-01-01 and since the URL is different it fails to validate the signature.

For reference, Symfony\Component\HttpFoundation\Request::normalizeQueryString() is where it sorts the query string keys

In my middleware I had used URL::to($request->getRequestUri()) to get the URL without sorting the query string parameters. There might be a more elegant way to get the un-modified URL but that worked for me.

Update I ended up using $url = $request->getSchemeAndHttpHost().$request->getRequestUri(); to get the URL

Dependency on League/URL

When installing the Laravel URL Signer component I get the message "Package league/url is abandoned, you should avoid using it. Use league/uri instead."

Do you have plans to update this dependency? I briefly tried to Install League/URI, but that package has further dependencies and I'm not sure if those would pose any downstream problems with Laravel URL Signer.

Thanks ..
-martin.

Lumen Support?

Would love to use this but working with Lumen at the moment.

Real world usage of this package ?

Hello,

Your open source packages are great !

I'm considering using this one for a file-sharing app (with private share links of course !). I have not worked at lot with secure urls and I'm not sure if this library will be up to the task.

It would be nice to have a list with some projects that use it and are online (assuming there are any 😅 ) so I could see what was done with it.

Also, I see the name MD5UrlSigner. In my head MD5 != secure. Should I use another hashing function to make it more secure ?

ErrorException in BaseUrlSigner.php line 44: The signature key is empty (View: plan.blade.php)

laravel-url-signer is working perfectly fine on my local dev machine. When accessing url-signer on production i get

ErrorException in BaseUrlSigner.php line 44: The signature key is empty (View: plan.blade.php)

signature key is set in config/laravel-url-signer.php:
'signatureKey' => config('app.key'),

app.key is set:
'key' => env('APP_KEY'),

APP_KEY is set in .env:
APP_KEY=base64:pCeC0it .... .... ....

Link prematurely expiring?

Hi,

This package is working locally, but as soon as i deploy to production any links generated by this package are returning that they are invalid.

Example link: https://example.com/approve/8?expires=1519637818&signature={hash}

If you check that timestamp, you will see it is for 7 days time, however it returns false on the validate method.

After modifying the source files to do a check, it's this code which is failing:

        if (!$this->hasValidSignature($url)) {
            return false;
        }

The site is working locally.. and my .env file does have an APP_KEY - help.

Methode validate seems not to be tatic

Hi i've got this error where trying to validate url through UrlSigner::validate("url...")

Non-static method Spatie\UrlSigner\UrlSigner::validate() cannot be called statically, assuming $this from incompatible context

Any help would be greatly appreciated, Thanks

Make Url Expired by simply call a function

Can make the url expired just by simply call a function? ,
Right now from what i see , all the url is expired based on time (hours/days)
I want simply make the url expired by simply call a function ,
Any solution to my problem?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.