Home > Net >  Laravel 8 - How to implement simple API key authentication
Laravel 8 - How to implement simple API key authentication

Time:11-04

I am trying to implement a very simple prototype (non-production) authentication system for my API in Laravel 8. My goal is for any user with the hard coded API key to be able to use the endpoints. Otherwise, they will get a 401 error at all endpoints. Users must include the API key as a URI parameter, with the format in the below example:

'hostAddress'/api/endpoint1?apikey='APIkey'

Where 'hostAddress' represents the host ipv6 address and 'APIkey' represents the hard coded API key.

Every search I make for this problem leads me to the Laravel 8 documentation (https://laravel.com/docs/8.x/authentication). However, the authentication solutions in the documentation are much more complex than what I am looking for.

How I can implement this simple authentication system without the use of complex Laravel packages such as Passport and Sanctum?

CodePudding user response:

Just use middleware. Add your key in config/app.php

[
  'api_key' => env('API_KEY'),
]

Create middleware and add it to App\Http\Kernel

namespace App\Http\Middleware;
class ApiKeyMiddleware
{
  public function handle($request, Closure $next)
  {
    if(!$key = $request->get('apikey') or $key !== config('app.api_key'){
      throw new AuthenticationException('Wrong api key');
    }
  }
}
class Kernel extends HttpKernel
{
  protected $middlewareGroups = [
        'api' => [
            App\Http\Middleware\ApiKeyMiddleware::class
            'throttle:300,1',
            'bindings',
        ],
  ]
}
  • Related