简体   繁体   中英

Lumen API authentication using API key strategy

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.

  1. 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?

  2. 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.

  1. If you use HTTPS to send requests, even if the request is intercepted the data can't be decrypted without the private key of the server. Even if a man in the middle attack to be successful client side can identify it having an untrusted certificate. If you are paranoid of the security you can use RSA signature verification process to verify the authenticity of the client. Client side will have a key pair where the private key resides in client application and each request will be signed with the private key and server will verify the authenticity using client's public key. See the example here .

  2. PHP being one of the most used server side scripting languages it is designed to read & write on databases each request. To improve the efficiency you can use caching methods using in memory databases like Redis explained here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM