Masoud Tavakkoli
Masoud Tavakkoli

Reputation: 1020

how to control api_key in Laravel API route

I write an API using Laravel, I want to define an api_key like this link

http://example.com/api/USER_API_KEY/json/method

this API_KEY defines that the user has an access to the API or not. To implement this issue, I have to check the database to see what's going on.

How can I implement this in my api.php route

api.php

Route::prefix('json')->group(function () {
    Route::match(['get', 'post'], '/', function () {
        return response('No functionality found', 200)
            ->header('Content-Type', 'application/json');
    });

    Route::match(['get', 'post'], '/SingleSend', 'ApiControlller@SingleSend');
});

Upvotes: 0

Views: 175

Answers (1)

Leo
Leo

Reputation: 7420

Create a middleware by running the command in console:

php artisan make:middleware <MiddlewareName>

This command creates your middleware class in app/Http/Middleware

Open middleware class and add the logic to the middleware to verify user token.

You will have a method handle() defined on middleware there you want to check if token is valid or not.

public function handle($request, Closure $next, $role)
{
   $apiToken = $request->get('token', null);

   //here you can get user token from database and compare with the apiToken

   if(empty($apiToken)){

        return response('forbbiden', 403);
    }
   return $next($request);
}

If you want a middleware to run on every request, go to app/Http/kernel.php under $routeMiddleware and add your middleware.

protected $routeMiddleware = [
    ...
    'verify-api-token' => \App\Http\Middleware\YourMiddlwareName::class,
    ...
];

Attaching your middleware to the route:

Route::prefix('json')->group(['middleware' => 'verify-api-token'], function () {
    Route::match(['get', 'post'], '/', function () {
        return response('No functionality found', 200)
            ->header('Content-Type', 'application/json');
    });

    Route::match(['get', 'post'], '/SingleSend', 'ApiControlller@SingleSend');
});

Upvotes: 1

Related Questions