rohsyl / laravel-otc
Laravel 单次代码认证
Requires
- php: >=8.0.2
- illuminate/contracts: ^9.0
- spatie/laravel-package-tools: ^1.13.0
Requires (Dev)
- laravel/pint: ^1.0
- nunomaduro/collision: ^6.1
- nunomaduro/larastan: ^2.0.1
- orchestra/testbench: ^7.0
- pestphp/pest: ^1.21
- pestphp/pest-plugin-laravel: ^1.1
- phpstan/extension-installer: ^1.1
- phpstan/phpstan-deprecation-rules: ^1.0
- phpstan/phpstan-phpunit: ^1.0
- phpunit/phpunit: ^9
- spatie/laravel-ray: ^1.26
README
Laravel 单次代码认证允许您通过邮件发送单次代码以认证您的用户。
安装
您可以通过 composer 安装此软件包
composer require rohsyl/laravel-otc
运行安装程序
php artisan otc:install
配置
编辑 config/otc.php
return [ 'notifier_class' => \Illuminate\Support\Facades\Notification::class, 'notification_class' => \rohsyl\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' => \rohsyl\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()
此方法将返回
true
或false
。
如果用户未认证,您可以返回一个错误
if(!Otc::check()) { return Otc::unauthorizedResponse($user); }
此响应将返回以下内容的 401 http 错误。
{ "request_code_url": ".../vendor/rohsyl/laravel-otc/auth/request-code", "request_code_body": { "type": "user", "identifier": "test@test.com" } }
您必须使用 request_code_url
作为请求代码的 URL(看起来很明显),并且您必须以 json 格式传递 request_code_body
作为正文!
请求代码
发送一个 POST 请求
POST /vendor/rohsyl/laravel-otc/auth/request-code
带有正文
{ "type": "user", "identifier": "test@test.com" }
您需要发送您的可认证实体的
type
和identifier
。
如果可用,将向相应的实体发送电子邮件。电子邮件将包含代码。
请求令牌
发送一个 POST 请求
POST /vendor/rohsyl/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/rohsyl/laravel-otc/*',
],
测试
composer test
变更日志
请参阅 CHANGELOG 了解最近更改的更多信息。
贡献
请参阅 CONTRIBUTING 了解详细信息。
安全
如果您发现任何与安全相关的问题,请使用问题跟踪器。
致谢
许可
MIT 许可证(MIT)。请参阅 许可文件 了解更多信息。