coucounco/laravel-otc

Laravel 单次代码认证

v2.0.0 2024-09-09 10:24 UTC

This package is auto-updated.

Last update: 2024-09-09 11:50:16 UTC


README

Latest Version on Packagist CI Total Downloads

Laravel 单次代码认证允许您通过邮件发送一次性代码以认证您的用户。

安装

您可以通过 composer 安装此包

composer require coucounco/laravel-otc

运行安装程序

php artisan otc:install

配置

编辑 config/otc.php

return [
    'notifier_class' => \Illuminate\Support\Facades\Notification::class,
    'notification_class' => \coucounco\LaravelOtc\Notifications\OneTimeCodeNotification::class,

    'authenticatables' => [
        'user' => [
            'model' => \App\Models\User::class,
            'identifier' => 'email',
        ]
    ]
];

notifier_class

定义将调用哪个类来发送通知。默认情况下,它使用 Laravel 的 Notification 门面。

'notifier_class' => \Illuminate\Support\Facades\Notification::class,

notification_class

定义将发送什么通知。

'notification_class' => \coucounco\LaravelOtc\Notifications\OneTimeCodeNotification::class,

您可以将此类替换为任何其他通知,您将接收一个 OtcToken $token 作为构造函数参数

public function __construct(OtcToken $token) {
    $this->token = $token;
}

您可以从 $token 变量访问需要发送的代码

$token->code

authenticatables

此数组将定义可以用于认证的一组实体。它类似于简化版的 Laravel 守卫。我可能会将其移动到守卫中。主要目标是设置模型和用于在数据库中查找模型所用的列。

  • user 是 "守卫"/类型的名称
  • model 是相应的 eloquent 模型
  • identifier 是用于查找对应用户的标识符列
'user' => [
    'model' => \App\Models\User::class,
    'identifier' => 'email',
]

使用方法

检查

检查用户是否已认证

Otc::check()

此方法将返回 truefalse

如果用户未认证,您可以返回一个错误

if(!Otc::check()) {
    return Otc::unauthorizedResponse($user);
}

此响应将返回以下内容的 401 http 错误。

{
    "request_code_url": ".../vendor/coucounco/laravel-otc/auth/request-code",
    "request_code_body": {
        "type": "user",
        "identifier": "test@test.com"
    }
}

您必须使用 request_code_url 作为请求代码的 URL(看起来很明显),并且必须将 request_code_body 作为 json 格式的正文传递!

请求代码

发送 POST 请求

POST /vendor/coucounco/laravel-otc/auth/request-code

带有正文

{
    "type": "user",
    "identifier": "test@test.com"
}

您需要发送您的认证实体的 typeidentifier

如果可用,将向相应的实体发送电子邮件。电子邮件将包含代码。

请求令牌

发送 POST 请求

POST /vendor/coucounco/laravel-otc/auth/code

带有正文

{
    "type": "user",
    "identifier": "test@test.com",
    "code": <code>
}

您需要发送从用户处获取的 code,该代码可以从表单或其他任何地方获取。

您将收到一个令牌

{
    "token": "9vov6FjW47v6JjH...4iPzPH0PwpwdE"
}

您可以使用此令牌进行所有后续请求。

已认证的请求

当您有令牌时,您可以将它与您的请求一起发送以进行认证。

在头中传递

Authorization: Bearer <token>

或在查询字符串中

?token=<token>

故障排除

CORS

如果您使用 fruitcake/laravel-cors 来管理您的应用中的 CORS。当调用此包的端点时,您将获得 CORS 错误

您需要在 config/cors.php 中的 paths 数组中添加一个新路径

    'paths' => [
        // ...
        'vendor/coucounco/laravel-otc/*',
    ],

测试

composer test

变更日志

有关最近更改的更多信息,请参阅 CHANGELOG

贡献

有关详细信息,请参阅 CONTRIBUTING

安全

如果您发现任何安全问题,请使用问题跟踪器。

鸣谢

许可

MIT 许可证(MIT)。有关更多信息,请参阅 许可文件