I'm working on a REST API using Lumen. (version 8). And I need to implement a API key based auth for my REST API. For example, I will generate an API key and will give it to 3rd parties who need to use my API. To generate this key, I'm using JWT. Then I save the key in the database.
<?php
namespace App\Http\Middleware;
use App\ApiKey;
use Closure;
class ApiAuthMiddleware
{
public function handle($request, Closure $next)
{
$tokenValid = ApiKey::where('api_key', $request->header('Authorization'))->exists();
if (!$tokenValid) {
return response()->json('Unauthorized', 401);
}
return $next($request);
}
}
This is my custom designed code to check API key in the database. I have some major security based concerns.
Other 3rd parties will send this token in the header and anyone can read the payload can get the header and send me a request with the same header. How to prevent this? Is there something to do with a client secret key?
Is it practical to check the MySQL database in each request? Is that an unnecessary workload for the database? Can we replace this with a small Redis instance? Is that secure?
We can set token like this:
Redis::set('token', 'jwt_token_here');
Finally, is there a library to manage this without using my customized code? I think it is more secure and efficient.
Thank you in advance.