uogsoe/basic-api-token-middleware

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

1.1.1 2018-04-19 11:40 UTC

This package is auto-updated.

Last update: 2024-08-29 04:42:11 UTC


README

这是一个简单的基于密钥的Laravel中间件。它适合我们常见的用例,即内部应用程序需要访问其他内部应用程序(机器到机器),而无需处理oauth等烦恼。

安装

您应该能够使用composer将其拉入

composer require uogsoe/basic-api-token-middleware

然后您必须发布数据库迁移和ApiKey模型

php artisan vendor:publish

并从列表中选择 UoGSoE\ApiTokenMiddleware\ApiTokenServiceProvider。然后运行迁移

php artisan migrate

用法

首先,您为消费'服务'(例如,远程客户端)创建一个令牌

php artisan apitoken:create testservice

这将创建令牌并将其显示给您。您需要记下令牌,因为您的客户端将需要使用它来访问路由。

现在,在您的 routes/api.php 文件中,您可以使用中间件包装端点

Route::group(['middleware' => 'apitoken:testservice'], function () {
    Route::get('/hello', function () {
        return 'hello';
    });
});

如果您尝试在不传递令牌的情况下访问该路由,您将收到401响应

curl -kv https://my-project.test/api/hello
...
HTTP/2 401
{"message":"Unauthorized"}

因此,传递您上面创建的令牌,它应该让您通过

curl -kv https://my-project.test/api/hello?api_token=jT7ryt28gi3YCvgE4WvluO1uVcb0ndVx
...
HTTP/2 200
hello

您可以通过多种方式传递令牌,如上述GET参数,bearer令牌标头或作为JSON主体的部分。例如

$this->withHeaders([
    'Authorization' => 'Bearer '.$tokenString,
])->get('https://my-project.test/api/hello');

$this->json('POST', 'https://my-project.test/api/hello', ['api_token' => $token]);

$this->call('POST', 'https://my-project.test/api/hello', ['api_token' => $token]);

如果您想将API控制分离,您可以在路由中使用多个服务令牌名称

Route::group(['middleware' => 'apitoken:testservice,anotherservice'], function () {
    Route::get('/hello', function () {
        return 'hello';
    });
});

还有一些Artisan命令可以帮助管理令牌

php artisan apitoken:list -- lists all current tokens
php artisan apitoken:regenerate -- create a new token for a given service
php artisan apitoken:delete -- deletes a given service token