code16/machina

Laravel 的机器到机器认证

v1.6.0 2024-04-04 08:08 UTC

This package is auto-updated.

Last update: 2024-09-04 09:03:08 UTC


README

此包是围绕 tymons\jwt-auth 的包装器,旨在为 Laravel 5.5+ 提供简单且灵活的机器到机器认证。

安装

    composer require code16/machina

配置

如果您想自定义一些默认选项,如包用于 /login/refresh 端点的前缀,您可以将它发布到您的应用程序文件夹

    php artisan config:publish code16/machina

然后运行以下命令,该命令将在您的 .env 文件中添加一个 JWT_SECRET 条目

    php artisan jwt:secret

定义机器守卫

config/auth.php

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'machina' => [
            'driver' => 'machina',
            'provider' => Api\ClientRepository::class,
        ],
    ],

创建一个 ClientRepository

此包不提供关于检索客户端的特定方式,而是提供了一个非常简单的方法,通过提供实现 Code16\Machina\ClientRepositoryInterface 的类来将其适配到您的应用程序。

示例

    namespace App;

    use Code16\Machina\ClientRepositoryInterface;

    class ClientRepository implements ClientRepositoryInterface
    {
        public function findByKey($key)
        {
            return User::find($key);
        }

        public function findByCredentials($client, $secret)
        {
            return User::where('id', $client)->where('secret', $secret)->first();
        }

    }

注意,在这里我们使用了标准的 App\User 模型数据库来识别我们的客户端,但您可以使用您喜欢的任何模型/字段。

保护路由

    Route::get('protected', 'ApiController@index')->middleware('auth:machina');

验证和获取令牌

/auth/login 端点发送带有 clientsecret 参数的 POST 请求

    {
        client : "1",
        secret : "x7jfajleug64hggi"
    }

如果凭证正确,API 将返回一个 JWT 令牌,可用于访问受保护的路由。

访问受保护的路由

有几种方法可以将令牌传递给请求

  • authorization 标头中传递令牌,格式如下: Bearer <token>

  • 作为查询参数传递令牌: https://app.dev/protected?token=<token>

实现客户端应用程序

对于您的客户端应用程序,您可以使用我们的配套包,machina client