Protecting Laravel Sites with IP Intelligence

Protecting Laravel Sites with IP Intelligence

Protecting Laravel Sites with IP Intelligence - In this article, we will cover a simple way of how we can use IP intelligence to detect unwanted connections and protect against insecure ..

Originally published by Samuel Oloruntoba at scotch.io

From the moment you publish a website, you need to be wary of security. From hackers to script-kiddies, you can’t always be sure of where the next attack could come from.

So, as developers, we are always on the prowl for the next best thing when it comes to protecting our website(s).

In this article, we will cover a simple way of how we can use IP intelligence to detect unwanted connections and protect against insecure requests.

Table of Contents

  • What is IP Intelligence
  • Getting Started
  • Making a Request to IPAPI’s Server
  • Creating Our Middleware
  • Improving for Performance
  • Conclusion
What is IP Intelligence

When most people hear IP intelligence, the thing that comes to mind is “locating users from their IP address”. But, it doesn’t stop there, IP intelligence can be used to accomplish many things:

  • Content personalization.
  • Currency detection.
  • Fraud prevention.
  • Time Zone lookup.
  • Language redirection.

The list above is just a handful of things that can be achieved using IP intelligence.

Building a service that can do all the things listed above can take a lot of time and resources. So, instead of building and managing such a service, that’s what the sponsor IPAPI of this article does.

Getting Started

Our firewall will be built as a middleware for our application, meaning a request coming into our app will pass through this “filter” and reject suspected bad actors.

For demonstrating how we could build a simple middleware to protect our apps, we will be creating a Laravel projectNote, the same can be done in any programming language of choice

composer create-project laravel/laravel firewall --prefer-dist

So, head over to IPAPI and create an account. After that, you’ll see a secret key that has a similar structure to 86ebc30b4adfc508e48bf1b489140fe3. Grab whatever your own is and add it to your .env file.

 IPAPI_ACCESS_KEY=86ebc30b4adfc508e48bf1b489140fe3

After that open config/services.php and add the following array value.

'ip' => [
    'key' => env('IPAPI_ACCESS_KEY'),
],

The last thing to do is to install GuzzleHttp which will be used to make a request to IPAPI’s server.

composer require guzzlehttp/guzzle

After that, we can then build our middleware.

Making a Request to IPAPI’s Server

So, IPAPI offers two endpoints for us to use.

  • api.ipapi.com/api/<ip> where we provide the IP we want to check.
  • api.ipapi.com/check will guess the incoming IP address and give a response (good for requests coming from the browser.

We are most interested in the first one because using the second one will retrieve the IP of our server instead of the incoming request. So, using the first one, we can capture the user’s IP and forward it to IPAPI.

After we create a request like:

GET https://api.ipapi.com/api/161.185.160.93?access_key=86ebc30b4adfc508e48bf1b489140fe3

The response will look something like this

{
    "ip": "161.185.160.93",
    "hostname": "161.185.160.93",
    "type": "ipv4",
    "continent_code": "NA",
    "continent_name": "North America",
    "country_code": "US",
    "country_name": "United States",
    "region_code": "NY",
    "region_name": "New York",
    "city": "Brooklyn",
    "zip": "11238",
    "latitude": 40.676,
    "longitude": -73.9629,
    "location": {
        "geoname_id": 5110302,
        "capital": "Washington D.C.",
        "languages": [
            {
                "code": "en",
                "name": "English",
                "native": "English"
            }
        ],
        "country_flag": "http://assets.ipapi.com/flags/us.svg",
        "country_flag_emoji": "🇺🇸",
        "country_flag_emoji_unicode": "U+1F1FA U+1F1F8",
        "calling_code": "1",
        "is_eu": false
    },
    "time_zone": {
        "id": "America/New_York",
        "current_time": "2018-09-24T05:07:10-04:00",
        "gmt_offset": -14400,
        "code": "EDT",
        "is_daylight_saving": true
    },
    "currency": {
        "code": "USD",
        "name": "US Dollar",
        "plural": "US dollars",
        "symbol": "$",
        "symbol_native": "$"
    },
    "connection": {
        "asn": 22252,
        "isp": "The City of New York"
    },
    "security": {
        "is_proxy": false,
        "proxy_type": null,
        "is_crawler": false,
        "crawler_name": null,
        "crawler_type": null,
        "is_tor": false,
        "threat_level": "low",
        "threat_types": null
    }
}

We can see that IPAPI does a lot of work for us. For this, however, for this article, we are interested in the “security” part of the response.

...
    "security": {
        "is_proxy": false,
        "proxy_type": null,
        "is_crawler": false,
        "crawler_name": null,
        "crawler_type": null,
        "is_tor": false,
        "threat_level": "low",
        "threat_types": null
    } ...

Taking a closer look at the security portion, we can see that IPAPI does a lot of checks for us. From giving the response a security rating, to checking if the incoming request is from the TOR network. It even tells us if a crawler is making the incoming request.

Creating Our Middleware

Middlewares are mechanisms that sit in-between an incoming request and your app. Scotch has a short intro to Laravel middlewares.

Now, we’ll move into the root of our project and run

php artisan make:middleware IPFirewall

After we’ve created the middleware, we can find it in app/Http/Middlewares/IPFirewall.php you will see something similar to;

<?php

namespace App\Http\Middleware;

use Closure;

class IPFirewall
{
/**

  • Handle an incoming request.
  • @param \Illuminate\Http\Request $request
  • @param \Closure $next
  • @return mixed
    */
    public function handle($request, Closure $next)
    {
    return $next($request);
    }
    }

So, to protect our server, we can do this:

public function handle($request, Closure $next)
{
$ip = $request->ip();
$key = config('services.ip.key');
$url = "http://api.ipapi.com/api/{$ip}?access_key={$key}&amp;security=1";

// make request
$client = new Client;
$response = $client-&gt;request('GET', $url);
$data = json_decode((string) $response-&gt;getBody(), true);

if (!array_key_exists('security', $data)) {
    return false;
}

return $data['security']['threat_level'] === 'high' ? abort(403) : $next($request);

}

From the request above:

  • We first get the incoming IP address of the user
  • Then we build our request to send to IPAPI,
  • When we get a response from IPAPI, we check if the security response exists
  • Then if the request threat level is high, we want to restrict user access.
Improving for Performance

The above solution is not the best implementation we have. Because this means that the request is going to slow down for every incoming request.

Because Laravel has a cache layer, we can use that to our advantage by doing

public function handle($request, Closure $next)
{
$ip = $request->ip();
$insecureRequest = Cache::remember("firewall_$ip", function() use ($ip) {
// build parameters
$key = config('services.ip.key');
$url = "http://api.ipapi.com/api/{$ip}?access_key={$key}&security=1";
// make request
$client = new Client;
$response = $client->request('GET', $url);
$data = json_decode((string) $response->getBody(), true);
if (!array_key_exists('security', $data)) {
return false;
}
return $data['security']['threat_level'] === 'high' ?? false;
});
return $insecureRequest ? abort(403) : $next($request);
}

Calling Cache::remember() will tell Laravel to fetch a value from the cache, if it doesn’t exist, it’ll run the closure and return the value from the closure to the cache.

Using the IP address as the unique key, Laravel will first try to fetch the IP’s threat status. If it the request is considered an insecure request, Laravel aborts. Otherwise, the request is allowed through, and we only need to perform the check every once in a while.

Conclusion

IPAPI is a great service used many companies, give them a shot and improve your application security.

Originally published by Samuel Oloruntoba at scotch.io

=========================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

☞ RESTful API with Laravel: Build a real API with Laravel

☞ Master Laravel - A php framework for Beginner to Advanced

☞ PHP with Laravel for beginners - Become a Master in Laravel

☞ Projects in Laravel: Learn Laravel Building 10 Projects

☞ Laravel 2019, the complete guide with real world projects

☞ Laravel for RESTful: Build Your RESTful API with Laravel

☞ Real Time Single Page Forum App with Pusher Laravel & vuejs

☞ Master Laravel PHP in 2019 for Beginners and Intermediate


Advantages of Hiring PHP Developer for your Website Project

Advantages of Hiring PHP Developer for your Website Project

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is...

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is to learn the language yourself. That’s why PHP developers are there to make your life easy. This article will give us the advantages and requirements of Hire PHP Developer for our very own website project.

First of all, let us understand the value the right developer brings to the project and why it is important for your business.

A website is a major component of any company/business and is very important for its face value, the way it represents the company on the internet is critical for any business to succeed. This is the reason why companies are looking for PHP developers who can develop their webpage.

If you're planning to do an online business, your PHP programmer will be the first person to transfer your thinking onto the webpage. You should, therefore, employ developers from PHP to make your hypothetical idea a reality.

With this software programming language, PHP developers all-around can easily build website frameworks, web content management systems, web template systems, and various other web-based designs.

Some of the reasons why we need to outsource these developers are:

Not everyone is the best in each field, all of us have our specific skills and talents hence, PHP developers are also the best at what they do. The time and money spent on the training of the in house employees would be saved if the professional PHP developers are hired. Instead of multitasking, if the employees were to focus on what they’re good at it would increase productivity too.

The PHP developers would be much more professional than the in-house workers. It would lead to the seriousness of work. Hence, on-time delivery is guaranteed with hired PHP developers.

In addition to these benefits, you would also be able to track your project through every stage in constant communication with your online team. These advantages make it incredibly popular and smart to hire a PHP developer.

The PHP developers have in-depth knowledge of PHP, HTML and various frameworks in terms of technical capabilities. Hiring PHP developers are advised to give your website a professional look based on PHP.

Much of web success depends on the involvement of social media. The developer can add to your social networking pages a feature that explicitly redirects visitors. In addition, SEO experts also suggest better connections to the website's social network.

Just like a tailor stitches our dresses according to our preferences and is ready to make last-minute changes. A PHP developer will also be available at the nick of your call to make the website just the way you want it to be and have a customized solution for every problem.

Read also: Why & How to Hire Dedicated PHP Developer

At some point in your business, you’re going to have problems regarding your webpage due to the rapidly changing technology, instead of struggling with ideas like these and not being able to come up with an appropriate solution a PHP web developer could help us with our problems just like any technician would help us with the problems we face in our offices or any architect would help us with designing the structure of a building or any interior designer would help us with setting up our home. The PHP development company are hubs of workers who would help us overcome these problems and are always there.

Source by

Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]

Laravel Framework Development Services | Laravel Web Development

CMARIX is leading Laravel Web application Development Service Provider with the track record of implementing diverse high-performance Laravel web applications with skilled Laravel developer team for clients across the globe<a href="https://www.cmarix.com/laravel-framework-development-services.html?utm_source=SB" target="_blank">.Continue</a>

CMARIX is leading Laravel Web application Development Service Provider with the track record of implementing diverse high-performance Laravel web applications with skilled Laravel developer team for clients across the globe.Continue