2017 © Pedro Peláez
 

library api-guard

A simple way of authenticating your APIs with API keys using Laravel

image

misfits/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  • Saturday, June 2, 2018
  • by Tjoosten
  • Repository
  • 1 Watchers
  • 0 Stars
  • 59 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 134 Forks
  • 5 Open issues
  • 41 Versions
  • 13 % Grown

The README.md

ApiGuard

Latest Stable Version Total Downloads, (*1)

Join the chat at https://gitter.im/chrisbjr/api-guard, (*2)

A simple way of authenticating your APIs with API keys using Laravel. This package uses the following libraries:, (*3)

Laravel 5.3, 5.4 and 5.5 is finally supported!

**Laravel 5.3.x onwards: ~4.*, (*4)

**Laravel 5.1.x to 5.2.x: ~3.*, (*5)

**Laravel 5.1.x: ~2.*, (*6)

**Laravel 4.2.x: ~1.* (Recently updated version for Laravel 4. Please note that there are namespace changes here), (*7)

**Laravel 4.2.x: 0.* (The version that most of you are using), (*8)

Quick start

Installation for Laravel 5.3 to 5.4

Run composer requiremisfits/api-guard 4.*`, (*9)

In Laravel 5.5 and higher the service provider will automatically get registered. In older versions of the framework just add the service provider in config/app.php file:, (*10)

'providers' => array(

    ...
    Chrisbjr\ApiGuard\Providers\ApiGuardServiceProvider::class,
),

Now publish the migration and configuration files for api-guard:, (*11)

$ php artisan vendor:publish --provider="Chrisbjr\ApiGuard\Providers\ApiGuardServiceProvider"

Then run the migration:, (*12)

$ php artisan migrate

It will setup api_keys table., (*13)

Generating your first API key

Once you're done with the required setup, you can now generate your first API key., (*14)

Run the following command to generate an API key:, (*15)

php artisan api-key:generate, (*16)

Generally, the ApiKey object is a polymorphic object meaning this can belong to more than one other model., (*17)

To generate an API key that is linked to another object (a "user", for example), you can do the following:, (*18)

+php artisan api-key:generate --id=1 --type="App\User", (*19)

To specify that a model can have API keys, you can attach the Apikeyable trait to the model:, (*20)

use Chrisbjr\ApiGuard\Models\Mixins\Apikeyable;

class User extends Model
{
    use Apikeyable;

    ...
}

This will attach the following methods to the model:, (*21)

// Get the API keys of the object
$user->apiKeys();

// Create an API key for the object
$user->createApiKey();

To generate an API key from within your application, you can use the following method in the ApiKey model:, (*22)

$apiKey = Chrisbjr\ApiGuard\Models\ApiKey::make()

// Attach a model to the API key
$apiKey = Chrisbjr\ApiGuard\Models\ApiKey::make($model)

Usage

You can start using ApiGuard by simply attaching the auth.apikey middleware to your API route:, (*23)

Route::middleware(['auth.apikey'])->get('/test', function (Request $request) {
    return $request->user(); // Returns the associated model to the API key
});

This effectively secures your API with an API key which needs to specified in the X-Authorization header. This can be configured in config/apiguard.php., (*24)

Here is a sample cURL command to demonstrate:, (*25)

curl -X GET \
  http://apiguard.dev/api/test \
  -H 'x-authorization: api-key-here'

You might also want to attach this middleware to your api middleware group in your app/Http/Kernel.php to take advantage of other Laravel features such as throttling., (*26)

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    ...

    'api' => [
        'throttle:60,1',
        'bindings',
        'auth.apikey',
    ],
];

If you noticed in the basic example, you can also access the attached model to the API key by calling $request->user(). We are attaching the related model in this method because in most use cases, this is actually the user., (*27)

Accessibility to user data from controller

This library will attach the authenticated user information via middleware inject in AuthenticateApiKey, So to access user information inside a controller do the following:, (*28)

  1. Add auth.apikey to $middlewareGroups in app/Http/Kernel.php:
/**
 * The application's route middleware groups. 
 * 
 * @var array
 */
protected $middlewareGroups = [
    ...
    'api' => [
        'throttle:60,1',
        'bindings', 
        'auth.apikey', // here
    ]
];
  1. Access to user information:
$apiKey = request()->apiKey; // Will return an apiKey information instance

The output will look like:, (*29)

{
    "id": 25, // ID field in api_keys table
    "apikeyable_id": 1, // Reference to user, person, or any resource
    "apikeyable_type": "App\\User", // Api key type. (model)
    "key": "e8655df75b449878d48ed6ece31719513828a05c", // Api token key
    "last_ip_address": "192.168.10.1", // Last origin request
    "last_used_at": {
        "date": "2017-07-24 10:17:53.868782",
        "timezone_type": 3,
        "timezone": "Asia/Riyadh"
    },
    "created_at": "2017-07-24 09:17:18",
    "updated_at": "2017-07-24 10:17:53",
    "deleted_at": null,
    "apikeyable": {
        "id": 1,
        "name": "John Doe",
        "email": "name@example.com",
        "mobile": "+966555555555",

        ...

        "created_at": "2017-07-23 14:08:25",
        "updated_at": "2017-07-23 14:08:25",
    }
}

Unauthorized Requests

Unauthorized requests will get a 401 status response with the following JSON:, (*30)

{
  "error": {
    "code": "401",
    "http_code": "GEN-UNAUTHORIZED",
    "message": "Unauthorized."
  }
}

ApiGuardController

The ApiGuardController takes advantage of Fractal and api-response libraries., (*31)

This enables us to easily create APIs with models and use transformers to give a standardized JSON response., (*32)

Here is an example:, (*33)

Let's say you have the following model:, (*34)

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $fillable = [
        'name',
    ];
}

You can make a basic controller which will return all books like this:, (*35)

use Chrisbjr\ApiGuard\Http\Controllers\ApiGuardController;
use App\Transformers\BookTransformer;
use App\Book;

class BooksController extends ApiGuardController
{
    public function all()
    {
        $books = Book::all();

        return $this->response->withCollection($books, new BookTransformer);
    }
}

Now, you'll need to make the transformer for your Book object. Transformers help with defining and manipulating the variables you want to return to your JSON response., (*36)

use League\Fractal\TransformerAbstract;
use App\Book;

class BookTransformer extends TransformerAbstract
{
    public function transform(Book $book)
    {
        return [
            'id'         => $book->id,
            'name'       => $book->name,
            'created_at' => $book->created_at,
            'updated_at' => $book->updated_at,
        ];
    }
}

Once you have this accessible in your routes, you will get the following response from the controller:, (*37)

{
  "data": {
    "id": 1,
    "title": "The Great Adventures of Chris",
    "created_at": {
      "date": "2017-05-25 18:54:18",
      "timezone_type": 3,
      "timezone": "UTC"
    },
    "updated_at": {
      "date": "2017-05-25 18:54:18",
      "timezone_type": 3,
      "timezone": "UTC"
    }
  }
}

More examples can be found on the Github page: https://github.com/ellipsesynergie/api-response., (*38)

To learn more about transformers, visit the PHP League's documentation on Fractal: Fractal, (*39)

API Validation Responses

ApiGuard comes with a request class that can handle validation of requests for you and throw a standard response., (*40)

You can create a Request class as you usually do but in order to get a standard JSON response you'll have to extend the ApiGuardFormRequest class., (*41)

use Chrisbjr\ApiGuard\Http\Requests\ApiGuardFormRequest;

class BookStoreRequest extends ApiGuardFormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required',
        ];
    }
}

Now you can use this in your controller as you normally do with Laravel:, (*42)

use Chrisbjr\ApiGuard\Http\Controllers\ApiGuardController;
use App\Transformers\BookTransformer;
use App\Book;

class BooksController extends ApiGuardController
{
    public function store(BookStoreRequest $request)
    {
        // Request should already be validated

        $book = Book::create($request->all())

        return $this->response->withItem($book, new BookTransformer);
    }
}

If the request failed to pass the validation rules, it will return with a response like the following:, (*43)

{
  "error": {
    "code": "GEN-UNPROCESSABLE",
    "http_code": 422,
    "message": {
      "name": [
        "The name field is required."
      ]
    }
  }
}

The Versions

02/06 2018

dev-master

9999999-dev https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

The Development Requires

laravel api json rest api keys api authentication

11/05 2018

4.5.1

4.5.1.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

The Development Requires

laravel api json rest api keys api authentication

11/05 2018

dev-develop

dev-develop https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

The Development Requires

laravel api json rest api keys api authentication

10/05 2018

4.5.0

4.5.0.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

The Development Requires

laravel api json rest api keys api authentication

22/03 2018

dev-add-code-of-conduct-1

dev-add-code-of-conduct-1 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

The Development Requires

laravel api json rest api keys api authentication

13/03 2018

4.4.4

4.4.4.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

The Development Requires

laravel api json rest api keys api authentication

13/03 2018

4.3.2

4.3.2.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

The Development Requires

laravel api json rest api keys api authentication

13/03 2018

4.3.3

4.3.3.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

The Development Requires

laravel api json rest api keys api authentication

13/03 2018

4.3.1

4.3.1.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

The Development Requires

laravel api json rest api keys api authentication

26/09 2017

v4.1.0

4.1.0.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

The Development Requires

laravel api json rest api keys api authentication

27/05 2017

v4.0.0

4.0.0.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

The Development Requires

laravel api json rest api keys api authentication

26/10 2016

1.1.x-dev

1.1.9999999.9999999-dev https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

17/02 2016

3.0.x-dev

3.0.9999999.9999999-dev https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

13/02 2016

v3.0.3

3.0.3.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

04/02 2016

v3.0.1

3.0.1.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

01/02 2016

v3.0.0

3.0.0.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

06/08 2015

v2.3.0

2.3.0.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

25/06 2015

v2.2.3

2.2.3.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

16/06 2015

v2.2.2

2.2.2.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

27/05 2015

v1.1.3

1.1.3.0 https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

27/05 2015

v1.1.2

1.1.2.0 https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

03/05 2015

v1.1.1

1.1.1.0 https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

03/05 2015

v2.2.1

2.2.1.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

02/05 2015

v1.1

1.1.0.0 https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

23/04 2015

v2.2.0

2.2.0.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

17/04 2015

v2.1.1

2.1.1.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

08/04 2015

v2.1.0

2.1.0.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

07/04 2015

v2.0.1

2.0.1.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

27/03 2015

v2.0.0

2.0.0.0 https://github.com/chrisbjr/api-guard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

27/03 2015

v1.0

1.0.0.0 https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

10/01 2015

v0.7

0.7.0.0 https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

18/11 2014

v0.6

0.6.0.0 https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

18/10 2014

v0.5

0.5.0.0 https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

30/09 2014

v0.4

0.4.0.0 https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

11/07 2014

v0.3

0.3.0.0 https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

27/06 2014

v0.2

0.2.0.0 https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api json rest api keys api authentication

15/06 2014

v0.1

0.1.0.0 https://github.com/chrisbjr/ApiGuard

A simple way of authenticating your APIs with API keys using Laravel

  Sources   Download

The Requires

 

laravel api rest controller api keys