chrisidakwo / laravel-auth-identifiers
Laravel自定义认证,可选择使用自定义密码验证实现
1.0.3
2024-02-13 13:29 UTC
Requires
- php: >=8.1
- illuminate/auth: ^5.8 || ^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0
This package is auto-updated.
Last update: 2024-09-24 15:45:45 UTC
README
Laravel Auth Identifier 是一个小型库,允许您使用自定义认证标识符,例如:电子邮件、密码、电话号码或PIN
来在您的应用程序中认证用户。它还允许您使用类或闭包函数实现自定义密码验证器。
安装
composer require chrisidakwo/laravel-auth-identifiers
安装后,将服务提供者添加到config/app.php
文件中的提供者数组中。确保它位于App\Providers\AuthServiceProvider::class
下方,以避免Laravel的默认AuthServiceProvider
覆盖此库的实现。
ChrisIdakwo\Auth\Providers\CustomAuthServiceProvider::class
Laravel 5.5使用包自动发现,因此不需要您手动添加ServiceProvider。
配置
仅在需要使用自定义密码验证器时发布配置文件
php artisan vendor:publish --tag=custom-auth
用户模型
更新User
模型,使用ChrisIdakwo\Auth\Traits\CustomAuthUser
特质。
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use ChrisIdakwo\Auth\CustomAuthUser; class User extends Authenticatable { use Notifiable, CustomAuthUser; /** * Get the name of the unique identifier for the user. * * You can list as many items as possible in the array, or just one item. * * @return array */ public function getAuthIdentifiersName(): array { return ['email', 'username', 'phone_number', 'pin']; } }
这样,您就可以通过电子邮件、用户名、电话号码或PIN代码之一来认证用户。
认证驱动程序
在config/auth.php
文件中更新用户的提供者驱动程序,如下所示
<?php return [ // ... 'providers' => [ 'users' => [ 'driver' => 'custom-auth', 'model' => App\Models\Auth\User::class, ], ], // ... ];
使用方法
<?php use Illuminate\Support\Facades\Auth; $data = ['identifier' => 'johndoe@desevens.com', 'password' => 'foobar']; if (Auth::attempt($data)) { // Continue with whatever you want to do }