ohffs/simple-api-key-middleware

非常基础的Laravel API密钥中间件

1.0.3 2022-04-03 14:55 UTC

This package is auto-updated.

Last update: 2024-08-30 01:38:18 UTC


README

这是一个非常基础的中间件,用于检查传入请求中的携带令牌。

安装

composer require ohffs/simple-api-key-middleware
php artisan migrate

迁移将创建一个名为simple_api_keys的新数据库表。您可以在包中的migrations/目录中查看详细信息。

使用方法

该包注册了一个中间件别名simple-api-key(映射到\Ohffs\SimpleApiKeyMiddleware\ApiKeyMiddleware)。要保护特定的路由,您可以这样做

Route::get('/secret-stuff', [SecretStuffController::class, 'show'])->middleware('simple-api-key');

请参阅Laravel文档以获取更多示例,例如路由组或默认中间件。

要使用CLI生成API密钥,您可以使用artisan命令

php artisan api-key:generate "Key for secret stuff"

这将创建具有该描述的密钥并显示生成的令牌。您可以通过这样做来删除密钥

php artisan api-key:remove 14-2398adshh2349addasd7213402

(其中14-2398...是您生成的令牌)。您还可以以编程方式创建令牌

$apikey = \Ohffs\SimpleApiKeyMiddleware\SimpleApiKey::generate('My new Token');
echo $apikey->plaintext_token;

plaintext_token仅在新生成的令牌上可用。

要使用令牌进行请求,您将其作为常规携带令牌传递。例如,使用curl

curl -H "Authorization: Bearer 12-sd8623hsdfi9823nsdf9sdf" https://example.com/secret-stuff

或使用Laravel的HTTP客户端

$response = Http::withToken('12-sd8623hsdfi9823nsdf9sdf')->get('https://example.com/secret-stuff');

配置

默认配置如下

    // default length of generated api keys
    'token_length' => env('API_KEY_LENGTH', 64),
    // enable caching of token lookups
    'cache_enabled' => env('API_KEY_CACHE_ENABLED', true),
    // time to cache token lookup results
    'cache_ttl_seconds' => env('API_KEY_CACHE_TTL', 60),

您可以设置这些环境变量,或者如果您运行php artisan vendor:publish并选择此包中的配置,则可以编辑生成的config/simple_api_keys.php文件。默认情况下,中间件将缓存令牌查找以节省每次都击中数据库。如果您不使用Redis等缓存,则可能想要禁用缓存。