Dylan  Iqbal

Dylan Iqbal

1560312456

Developing and Securing GraphQL APIs with Laravel

This article will show you how to use Laravel to implement a basic GraphQL API and how to secure it with Auth0. Throughout the article, you will learn how to implement the API step by step up to the final result.

Learn how to develop GraphQL APIs with Laravel and how to secure them with Auth0. You can find the final code on this GitHub repository.

The API You Will Build

The project you are going to build is an API providing a list of wines from all over the world. As mentioned before, you will build the API following the GraphQL model. This model allows a client to request the exact data it needs, nothing more, nothing less. You will implement the GraphQL API by using Laravel, one of the most popular PHP frameworks that allows you to set up an application in minutes by exploiting its powerful infrastructure. Finally, you will learn how easy it is to secure your GraphQL API with Auth0.

Before starting the project, ensure you have PHP and MySQL installed on your machine. You will also need Composer, a dependency manager for PHP.

Once you have these tools installed on your machine, you are ready to build the Wine Store API.

Setting up the Laravel PHP Project

The first step to create a Laravel project is to run the following command in a terminal:

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


This command asks Composer to create a Laravel project named winestore. The result is a new directory called winestore right where you ran the command. This directory will have a few files and subdirectories as shown in the following picture:

Don’t worry if you are not acquainted with Laravel’s structure. While you will build the application, you will learn the role of the most important directories and files.

Creating the Wine Store Model

Now you can start to modify the scaffolded project to implement the Wine Store data model.

Creating the Model and the Migration Script

For starters, you will need to use your terminal to move into the winestore project. After that you will run the following command:

# make sure you run it from the winestore directory
php artisan make:model Wine -m


This command will create the Wine model and, thanks to the -m flag, a migration script for database persistence.

The Wine model is implemented in the Wine.php file that you will find inside the app directory. In fact, the app directory contains the code representing the application’s domain. The content of the Wine.php file will be as follows:

// ./app/Wine.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Wine extends Model
{
    //
}


As you can see, this file defines an empty class extending the Model class from Eloquent. Eloquent is the Object-Relational Mapping (ORM) library shipped with Laravel.

The make:model command you ran a few moments ago also generated a migration script that defines the table structure needed to persist wines in a database. You will find this migration script in the database/migrations directory. If you open this directory, you will find three files whose name starts with a timestamp.

Laravel generated the first two files while initializing the project. These files and are related to the built-in user management feature provided by Laravel. The last file, ending with _create_wines_table.php, is the migration script for the Wine model. Migration scripts are used by Eloquent to create or update the schema of the tables in the application’s database. The timestamp prefix for each file helps Eloquent identify which migrations it needs to apply and in which order.

Now, open the file ending with _create_wines_table.php and put the following code inside it:

//database/migrations/yyyy_mm_dd_hhMMss_create_wines_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateWinesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('wines', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 50);
            $table->text('description');
            $table->string('color', 10);
            $table->string('grape_variety', 50);
            $table->string('country', 50);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('wines');
    }
}


Note: The up() is executed when an upgrade is applied to the database and the down() method is executed when a downgrade is applied.
As you can see, the code you inserted in this file is defining a few columns in your database (like name, description, and country). These columns will help you persist, in the database, the details of the wines.

Add Seeders to the Database

To test the API you are about to create, you need to feed some initial data to your database. To do this, you can create a seeder. Seeders are classes that populate database tables. To create a seeder, type the following command:

# from the winestore directory
php artisan make:seeder WinesTableSeeder


This command will generate a new file called WineTableSeeder.php file in the database/seeds directory. Open this file and change its content with the following one:

// ./database/seeds/WinesTableSeeder.php

<?php

use App\Wine;
use Illuminate\Database\Seeder;

class WinesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Wine::create([
            'name' => 'Classic Chianti',
            'description' => 'A medium-bodied wine characterized by a marvelous freshness with a lingering, fruity finish',
            'color' => 'red',
            'grape_variety' => 'Sangiovese',
            'country' => 'Italy'
        ]);

        Wine::create([
            'name' => 'Bordeaux',
            'description' => 'A wine with fruit scents and flavors of blackberry, dark cherry, vanilla, coffee bean, and licorice. The wines are often concentrated, powerful, firm and tannic',
            'color' => 'red',
            'grape_variety' => 'Merlot',
            'country' => 'France'
        ]);

        Wine::create([
            'name' => 'White Zinfandel',
            'description' => 'Often abbreviated as White Zin, it is a dry to sweet wine, pink-colored rosé',
            'color' => 'rosé',
            'grape_variety' => 'Zinfandel',
            'country' => 'USA'
        ]);

        Wine::create([
            'name' => 'Port',
            'description' => 'A fortified sweet red wine, often served as a dessert wine',
            'color' => 'red',
            'grape_variety' => 'Touriga Nacional',
            'country' => 'Portugal'
        ]);

        Wine::create([
            'name' => 'Prosecco',
            'description' => 'It is a dry white wine (brut) sometimes with a sweet flavor of green apple, honeydew melon, pear, and honeysuckle',
            'color' => 'white',
            'grape_variety' => 'Glera',
            'country' => 'Italy'
        ]);
    }
}


The run() method of the WinesTableSeeder class creates instances of the Wine model based on the specified values. Now, edit the DatabaseSeeder.php file you find in the same folder and invoke the WinesTableSeeder class inside the run() method. The following is the resulting code:

//database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(WinesTableSeeder::class);
    }
}


Now, open the .env file (which resides in the project’s root) and configure the database parameters shown below accordingly to your development environment:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret


Note: The up() is executed when an upgrade is applied to the database and the down() method is executed when a downgrade is applied.

docker run --name mysql \
   -p 3306:3306 \
   -e MYSQL_ROOT_PASSWORD=myextremellysecretpassword \
   -e MYSQL_DATABASE=homestead \
   -e MYSQL_USER=homestead \
   -e MYSQL_PASSWORD=secret \
   -d mysql:5.7


After this preparation, you are ready to create the table schema and to populate it. Type the following in a console window:

php artisan migrate:fresh --seed


This command will clear the database, execute the migration scripts, and run the database seeder.

Note: The up() is executed when an upgrade is applied to the database and the down() method is executed when a downgrade is applied.## Introducing GraphQL

So far, you defined the model and its database persistence. Now you can build the GraphQL API upon that.

Why GraphQL

The API you are going to implement is based on GraphQL, a specification from Facebook defining a query language for APIs. With respect to classic REST APIs, GraphQL allows you to define a single endpoint providing multiple resources to the clients. This contributes to reduce network traffic and to potentially speed up client applications. In addition, GraphQL allows a client to request just the data it needs, avoiding to receive a resource with all possible information. Again, this reduces the network traffic and optimizes the data processing on the client side.

GraphQL achieves this result by defining an abstract language to describe queries, schemas, and types, in a similar way as in a database. As said before, GraphQL is a specification. This means that GraphQL is independent of any programming language. If you want to use it in your application, you need to choose among the several available implementations available in almost any language.

Installing the GraphQL Library

To support GraphQL in the application you’re going to build you need to install a library that allows you to define schemas and queries in a simple way. The Laravel GraphQL library is one of the best for this purpose. To install it, issue the following command from the project root:

# issue this from the winestore directory:
composer require rebing/graphql-laravel


After the installation, you need to run the following command:

php artisan vendor:publish --provider="Rebing\GraphQL\GraphQLServiceProvider"


This command extracts the graphql.php configuration file from the vendor folder and put it into the config folder. This is a common approach that allows you to get one or more configuration files from a third party package so that you can change it for the needs of your application. You will use the graphql.php file later.

Creating the GraphQL API Schema

Since GraphQL is a query language, you need to know how you can build your query, what type of object you can receive as a response, and what fields you can request from the server. A GraphQL API endpoint provides a complete description of what your client can query. This description is called schema, a collection of data defining the queries that a client can request, the type of the returned resources, the allowed change requests to the resources, also known as mutations, and others.

To keep things simple, your API will allow you to retrieve the list of wines in the Wine Store and a specific wine. So its schema will consist of queries and types.

Creating the Wine Type

You will start by creating the API’s schema by defining the resource returned. To do this, create the GraphQL directory inside the app directory. This directory will contain all the definitions you need for the GraphQL schema of the API. In the app/GraphQL directory, create the Types directory and put in it a file called WineType.php with the following content:

// ./app/GraphQL/Types/WineType.php
<?php

namespace App\GraphQL\Types;

use App\Wine;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Type as GraphQLType;

class WineType extends GraphQLType
{
    protected $attributes = [
        'name' => 'Wine',
        'description' => 'Details about a wine',
        'model' => Wine::class
    ];

    public function fields()
    {
        return [
            'id' => [
                'type' => Type::nonNull(Type::int()),
                'description' => 'Id of the wine',
            ],
            'name' => [
                'type' => Type::nonNull(Type::string()),
                'description' => 'The name of the wine',
            ],
            'description' => [
                'type' => Type::nonNull(Type::string()),
                'description' => 'Short description of the wine',
            ],
            'color' => [
                'type' => Type::nonNull(Type::string()),
                'description' => 'The color of the wine',
            ],
            'grape_variety' => [
                'type' => Type::nonNull(Type::string()),
                'description' => 'The grape variety of the wine',
            ],
            'country' => [
                'type' => Type::nonNull(Type::string()),
                'description' => 'The country of origin of the wine',
            ]
        ];
    }
}


This file defines the WineType class by extending GraphQLType. Notice the definition of three protected attributes that assign the name of the type (Wine), a description (“Details about a wine”), and the model the type is associated with (the Wine class you defined before). The fields() method returns an array with the property definitions of the resources your API will expose.

Creating the GraphQL Queries

Now, create a Queries directory inside the ./app/GraphQL directory and put there a file called WinesQuery.php with the following content:

// ./app/GraphQL/Queries/WinesQuery.php

<?php

namespace App\GraphQL\Queries;

use App\Wine;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Query;

class WinesQuery extends Query
{
    protected $attributes = [
        'name' => 'wines',
    ];

    public function type()
    {
        return Type::listOf(GraphQL::type('Wine'));
    }

    public function resolve($root, $args)
    {
        return Wine::all();
    }
}


The WinesQuery class defined in this file represents a query that returns the list of wines from the Wine Store. You see that the query’s name is wines. The type() method returns the type of the resource returned by the query, expressed as a list of Wine type items. The resolve() method actually returns the list of wines by using the all() method of the Wine model.

In the same way, create a second file in the ./app/GraphQL/Queries directory called WineQuery.php (note that, this time, wine is singular). In this file, add the following code:

// ./app/GraphQL/Queries/WineQuery.php

<?php

namespace App\GraphQL\Queries;

use App\Wine;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Query;

class WineQuery extends Query
{
    protected $attributes = [
        'name' => 'wine',
    ];

    public function type()
    {
        return GraphQL::type('Wine');
    }

    public function args()
    {
        return [
            'id' => [
                'name' => 'id',
                'type' => Type::int(),
                'rules' => ['required']
            ],
        ];
    }

    public function resolve($root, $args)
    {
        return Wine::findOrFail($args['id']);
    }
}


In this case, the WineQuery.php file contains the definition of the query returning a single wine identified by the id field. Notice that the definition of the id argument specifies that the argument must be an integer and that it is mandatory (required). You should be able to read the meaning of the other members of the WineQuery class: the query’s name is wine, the returned type is Wine, and the returned resource is the wine identified by the id field.

Registering the Schema

After creating these types and queries, you need to register these items as the GraphQL schema in your API. So, open the graphql.php file (you will find it inside the config directory) and replace the current definition of 'schemas' with the following:

// ./config/graphql.php

// ...
    'schemas' => [
        'default' => [
            'query' => [
                'wine' => App\GraphQL\Queries\WineQuery::class,
                'wines' => App\GraphQL\Queries\WinesQuery::class,
            ]
        ],
    ],
// ...


Here you are saying that the schema of your GraphQL API consists of two queries named wine and wines, mapped to WineQuery and WinesQuery classes respectively.

Then, in the same file, replace the current definition of 'types' with the following:

// ./config/graphql.php

// ...
    'types' => [
      'Wine' => App\GraphQL\Types\WineType::class,
  ],
// ...


This definition maps the type GraphQL Wine to the WineType class.

Testing the API with GraphiQL

At this point, you are ready to use your GraphQL API. You could test the API by using [curl](https://curl.haxx.se/ "curl"), Postman, or any other HTTP client. But a specialized client can help you to better appreciate the power and the flexibility of GraphQL. One client that you can use is Electron GraphiQL, which is available for Windows, Linux, and Mac.

To use it, head to the GraphiQL homepage and download the version available for your operating system. After downloading and installing it, open the tool and change the GraphQL endpoint to [http://localhost:8000/graphql](http://localhost:8000/graphql "http://localhost:8000/graphql"). Right now, as you are not running your project yet, you will see a message saying Error: connect ECONNREFUSED 127.0.0.1:8000 on the right-hand side of the tool.

To fix that, head back to your terminal and issue the following commands:

# create the tables needed to persist wine
php artisan migrate

# seed the database with the test data
php artisan db:seed

# run the server
php artisan serve


As described in the comments above, the first two commands will create the database schema and seed it with the test data. Then, the last command will make your Laravel project run.

Now, back to the GraphiQL tool, paste the following query and press the play button (or you can hit Control + Enter to issue the query):

{
  wines {
    name, color
    }
}


The expression above specifies the name of the query (wines) and the fields of the resource you are interested in (name and color). The response to this request is a JSON object containing an array of wines with the requested fields only. You can try adding another field, like id or description, and issuing the query again to see what happens.

Securing Your Laravel and GraphQL API with Auth0

Now that you have a working GraphQL API, you probably want to restrict the access to it so that only authorized clients can consume it. One easy way to secure your API is to integrate it with Auth0. In this article, you will create an Auth0 API to represent your GraphQL and Laravel API, then you will configure a GraphiQL tool to issue authenticated requests to it. If you are developing a client application, you will need to learn how to integrate them with Auth0 to be able to consume your API. The way you integrate a client application with Auth0 depends on what type of client you are developing. Check Auth0’s docs to learn more.

Securing the API

The first step is to sign up for a free Auth0 account, if you don’t have one yet. Then, from your Auth0 dashboard, head to the APIs section, click on the Create API button, and fill the form as follows:

  • Name: “Laravel and GraphQL API”
  • Identifier: [https://laravel-graphql-api](https://laravel-graphql-api "https://laravel-graphql-api")
  • Signing Algorithm: RS256

Note: The up() is executed when an upgrade is applied to the database and the down() method is executed when a downgrade is applied.
After clicking on the Create button on this form, Auth0 will redirect you to the Quick Start section of your new API. From there, head to the Applications section of your dashboard and choose the “Laravel and GraphQL API (Test Application)” that Auth0 created for you. After clicking on it, Auth0 will show you a screen where you will see some properties of this application. Leave this page open and head back to your project.

Back in your project, open the .env file (you will find it in the project root) and add the following properties to it:

AUTH0_DOMAIN=https://<YOUR_DOMAIN>/
AUTH0_AUDIENCE=<YOUR_AUDIENCE>


You will have to replace <YOUR_DOMAIN> and <YOUR_AUDIENCE> with the properties from your Auth0 account. More specifically, you will have to replace the first placeholder with the Domain property of your Auth0 Application (e.g., blog-samples.auth0.com), and you will have to replace <YOUR_AUDIENCE> with your Auth0 API identifier (i.e., with [https://laravel-graphql-api](https://laravel-graphql-api "https://laravel-graphql-api")).

Now, you will have to create a middleware in your Laravel application to check if the HTTP requests sent to the API are authorized (i.e., if they contain valid access tokens). You can create a middleware by running the following command (you will need to stop the Laravel server by issuing Control + C first):

php artisan make:middleware CheckAccess


Issuing this command will create a new file called CheckAccess.php inside the ./app/Http/Middleware directory. Before changing this file, you will have to install the Auth0 PHP SDK:

composer require auth0/auth0-php


After installing this SDK, replace the contents of the ./app/Http/Middleware/CheckAccess.php file with this:

// ./app/Http/Middleware/CheckAccess.php

<?php

namespace App\Http\Middleware;

use Closure;
use Auth0\SDK\JWTVerifier;

class CheckAccess
{
    public function handle($request, Closure $next)
    {
        if (!empty(env('AUTH0_AUDIENCE')) && !empty(env('AUTH0_DOMAIN'))) {
            $verifier = new JWTVerifier([
                'valid_audiences' => [env('AUTH0_AUDIENCE')],
                'authorized_iss' => [env('AUTH0_DOMAIN')],
                'supported_algs' => ['RS256']
            ]);
            $token = $request->bearerToken();
            $decodedToken = $verifier->verifyAndDecode($token);
            if (!$decodedToken) {
                abort(403, 'Access denied');
            }
        }
        return $next($request);
    }
}


The handle() method of the CheckAccess middleware checks the access token only if you have configured your application by providing an Auth0 audience and domain (otherwise, it simply allows all requests). If that is the case, this method creates an instance of the JWTVerifier class based on the Auth0 configuration data you set in the .env file. Then this method retrieves the current bearer token from the HTTP request and verifies the JWTVerifier instance.

If the token is valid, the request is forwarded to GraphQL. Otherwise, an Access denied message is sent back.

Note: The up() is executed when an upgrade is applied to the database and the down() method is executed when a downgrade is applied.

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]


Once you have defined this middleware, you need to register it. To do this, open the ./app/Http/Kernel.php file and add, to the $routeMiddleware list, a mapping between a key (checkAccess) and the newly created middleware class (CheckAccess):

// ./app/Http/Kernel.php

protected $routeMiddleware = [
  // ... other mappings ...
  'checkAccess' => \App\Http\Middleware\CheckAccess::class,
];


As a final step, associate the CheckAccess middleware to the GraphQL schema by changing the ./config/graphql.php file as follows:

// ./config/graphql.php

// ...
'schemas' => [
    'default' => [
        'query' => [
            'wine' => App\GraphQL\Queries\WineQuery::class,
            'wines' => App\GraphQL\Queries\WinesQuery::class,
        ],
        'middleware' => ['checkAccess']
    ],
],
// ...


The middleware declaration asserts that Laravel will execute the checkAccess middleware for each request to the GraphQL schema. With that in place, you have finished securing your Laravel and GraphQL API with Auth0. To confirm that everything is in order, try using the GraphiQL tool to issue the same request as before (you will need to restart the server by issuing php artisan serve). If your configuration works, you will get an error.

Authorizing the GraphiQL Client

To be able to fetch your GraphQL API again, you will need to issue, from the GraphiQL client, requests with access tokens. As mentioned before, the way you get an access token varies depending on what type of client you are developing. However, in this article, for testing purposes, you will use a test token.

To get this token, open the APIs section in your Auth0 dashboard, then click on the API you created (“Laravel and GraphQL API”). Now, click on the Test tab then, if you scroll down a little bit, you will see a button called Copy Token. Click on this button to get a copy of the access token in your clipboard.

Now, head back to the GraphiQL tool, click on the blue Edit HTTP Headers button, click on the Add Header button, then add the following header:

  • Name: “Laravel and GraphQL API”
  • Identifier: [https://laravel-graphql-api](https://laravel-graphql-api "https://laravel-graphql-api")
  • Signing Algorithm: RS256

Make sure you use the access token you copied from your Auth0 dashboard (instead of eyJ...aEw), then hit save.

Now, click outside the dialog where you added the header, then hit the play button (or hit Control + Enter). If everything works as expected, you will see that you can fetch the list of wines again.

Summary

In this article, you learned how to create GraphQL APIs with Laravel and how to secure them with Auth0.

You started by creating a model with its migration scripts to persist data in a database. Besides that, you created a seeder for the model to populate the database with some initial test data. Then you continued to build your API by defining a GraphQL type and two GraphQL queries. After that, you used the GraphiQL browser-based client to test the GraphQL API interactively.

Finally, you used Auth0 to secure the GraphQL and to authorize the GraphQL client. What do you think about the process as a whole? Let us know on the comments box below.

#laravel #graphql #api

What is GEEK

Buddha Community

Developing and Securing GraphQL APIs with Laravel
sophia tondon

sophia tondon

1618970788

Top Laravel Development Company India | Laravel Development Services

Laravel is a popular framework for website development, acquiring 25.85% of the PHP framework market share. As a most admired framework among PHP frameworks, it is being utilized for e-commerce, enterprise, social media, and various different types of websites.

There are more than 1 million websites worldwide available over the web that are created using Laravel. Laravel framework is the first preference of PHP developers as it allows them to develop highly scalable, flexible, and faster web applications.

Surely, you, too, would want to deliver a splendid and unhindered user experience to your target audience over the web. Laravel framework can help you achieve this pursuit at ease; all you need to do is hire Laravel developers from reliable & coveted hosts. But! There is no shortage of Laravel development companies that promise to deliver an excellent solution, but only some are able to deliver top-notch quality.

Therefore, I have decided to enlist top Laravel development companies to help you find a reliable and expert host for web development. So, stay hooked with me till the end of this article and explore the best Laravel developers in 2021.

While creating this list, I have kept the following pointers in reflection:

Years of excellence (average 8 years)
Workfolio
Rewards & Recognition
Client rating & feedback
Hourly/Monthly Price
Number of happy clients
Number of successfully launched projects
Minimum man-years experience
So, let’s not waste a minute and glance at top Laravel development companies to hire for creating excellent web solutions.

Read More - https://www.valuecoders.com/blog/technology-and-apps/top-laravel-development-companies-to-hire-experts/

#hire a laravel developer #hire laravel developer #hire laravel developers #laravel developer for hire #laravel developers #laravel developers for hire

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Laravel Development Company

Laravel is the top MVC structured PHP framework used for developing web applications because it provides the best authentication & authorization system, easy mailing integration, error & exception handling, and testing automation. Using Laravel you can get the most robust and secured web application.

Develop web applications using Laravel with Skenix Infotech. Contact us now to know more about our Services & Pricing: https://www.skenix.com/laravel-website-development/

#laravel development company india #laravel development services #laravel development #laravel developers #laravel web development #hire laravel developers

Mansi Gandhi

Mansi Gandhi

1624438819

Laravel Development services india | Laravel Web Development Company - CMARIX Technolabs

CMARIX is one of the leading Laravel web development company at this time with a rating of 4.9/5 on Clutch. This is the best place where you could probably find the Best Laravel developers in the industry. Being one of the top Laravel development companies, CMARIX aims to create an atmosphere of collaboration, creativity, and excellence where everyone is doing their best work.

#laravel web development company india #laravel development services india #laravel web development company #laravel framework development services #laravel development #laravel development company

sophia tondon

sophia tondon

1620977020

Hire Laravel Developers | Laravel Development Company, Services India

Looking for a team of experienced offshore Laravel developers? Hire a top dedicated team of Laravel developers from India online with 6+ years of average experience on an hourly or dedicated (monthly) basis from ValueCoders and enjoy easy hiring, quality work, and on-demand scalability at up to 60% less cost.

Our offshore Laravel development experts are fully competent to build scalable, secure, and robust custom web apps suiting your business requirements.

First Time Right Process
Complete Control Over The Team
Certified Laravel Coders
Agile & DevOps Enablement
Non-Disclosure Agreement
No Contract Lock-Ins

Visit Us- https://www.valuecoders.com/hire-developers/hire-laravel-developers

#hire a laravel developer #hire laravel developer #laravel development #hire laravel experts #find laravel developers #laravel development services india