Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting certain routes access to localhost in Laravel

The database in my Laravel application is filled from a different Java application. These two applications (Java and Laravel) run on the same server. The Java application makes a POST request with data to the Laravel application. And the Laravel application inserts the sent data into the database.

The problem is that I cannot find a way to authenticate the request. I want Laravel application to accept that specific request (say, laravel.app/insert_data) only if the source is from the same server.

Currently the route laravel.app/insert_data is publicly accessible. How do I restrict to only localhost so that I don't accept data from unknown hosts.

One way is, I could fetch the HTTP headers from the request and filter. But I'm assuming Laravel has it's built in functionality to do such stuff.

like image 917
user2354302 Avatar asked Jan 14 '15 11:01

user2354302


2 Answers

You should use laravel filters.

One can be defined this way:

Route::filter('localCallOnly', function()
{
    //if IPs don't match - 404
    if (Request::server('SERVER_ADDR') != Request::server('REMOTE_ADDR'))
    {
        return App::abort(404);
    }
});

And later used for any route you want:

Route::get('insert_data', array('before' => 'localCallOnly', 'uses' => 'MyController@insertData'));

Basically this means that "localCallOnly" filter has to be applied to "insert_data" route. So if your rules (same IP) doesn't match the route (controller action) isn't executed.

like image 102
MaGnetas Avatar answered Oct 12 '22 09:10

MaGnetas


Depending on your environment, I would rather do this in the web server configuration itself. In a location config you could specify something like

Note the below is only for systems newer than apache 2.4. Permission designation changed

<Location '/url/here'>
Require IP 127.0.0.1
...
</Location>

Apache would then process any requests not from localhost with a 400 not authorized error. This would not work in a shared hosting environment, however.

like image 26
cumulose Avatar answered Oct 12 '22 09:10

cumulose