I recently had a need to expose an API with some very basic authentication requirements:
- The API cannot be accessible for everyone so there needs to be some level of authentication.
- The site providing the API does not offer user registration. If your site does have user registration and you want basic API authentication this approach is likely more suitable.
- Granting an API key will be a case-by-case manual process as opposed to on demand.
With these assumptions in mind, the powerful Laravel Passport package seemed to be overkill so I went with this approach using Laravel 5.6:
Step 1: Add an API_KEY value to your app’s .env file. If you need many keys, another option is to create a database table to store the keys.
API_KEY=p2lbgWkFrykA4QyUmpHihzmc5BNzIABq
Step 2: Create an API Token middleware using the make:middleware Artisan command.
php artisan make:middleware ApiToken
Step 3: Add the following code to the handle function in app\Http\Middleware\ApiToken.php which checks that the request’s token matches the expected token from the .env file. If you went with the database approach in step 1, you would modify this check to query the database for a matching token.
public function handle($request, Closure $next)
{
if ($request->api_token != env('API_KEY')) {
return response()->json('Unauthorized', 401);
}
return $next($request);
}Step 4: Register the middleware to the routeMiddleware array in the in app/Http/Kernel.php file.
protected $routeMiddleware = [
// ...
'apiToken' => \App\Http\Middleware\ApiToken::class,
];Step 5: Build a simple API route in the routes/api.php file that is protected by this middleware. Here’s an example:
Route::middleware('apiToken')->get('/example/{api_token}/{name}', function ($api_token, $name) {
return ['name' => $name];
});Now, when you access the route with an invalid token, you will get an unauthorized message. For example: https://yoursite.com/api/example/thisIsNotAValidApiToken/kevin
Response:
"Unauthorized"
Conversely, when you access the route with a valid API token, you will be authorized and get a response. For example: https://yoursite.com/api/example/p2lbgWkFrykA4QyUmpHihzmc5BNzIABq/kevin
Response:
{"name":"kevin"}Hopefully this is helpful if you have a similar use case.