rzb / social-auth
社交认证样板。
v1.0.9
2024-09-07 17:26 UTC
Requires
- illuminate/support: ^9.0|^10.0
- laravel/socialite: ^5.16
Requires (Dev)
- orchestra/testbench: ~7
- phpunit/phpunit: ~9.0
README
这是一个Socialite包装器,用于处理所有剩余的社交认证样板,暴露了可用的端点,可以一次性为任何模型提供多个提供者。
安装
- 通过Composer要求
$ composer require rzb/socialauth
- 运行自动发现的迁移
$ php artisan migrate
- 将合约和特质添加到用户模型中,或添加到您需要的任何模型中
<?php namespace App\Models\User; use Rzb\SocialAuth\Contracts\Resourceable as ResourceableContract; use Rzb\SocialAuth\Contracts\Sociable as SociableContract; use Rzb\SocialAuth\Traits\Resourceable; use Rzb\SocialAuth\Traits\Sociable; // ... class User extends AuthUser implements SociableContract, ResourceableContract { use Resourceable; use Sociable; // ... }
- (可选)如果您需要验证除用户以外的任何模型,添加/删除提供者或调整暴露的路由,发布配置文件
$ php artisan vendor:publish --provider="Rzb\SocialAuth\SocialAuthServiceProvider" --tag="config"
工作原理
默认情况下,安装后,该包自动暴露2个无状态的端点,并接受Google、Facebook和Twitter提供者进行用户模型验证。这些路由期望相同的2个段。
路由
- 返回给定提供者的认证URL,以便您的前端可以加载提供者的认证页面。
GET /auth/social/{provider}/{sociable}
- 回调路由,查找或创建给定的sociable模型,并返回其JsonResource。
POST /auth/social/{provider}/{sociable} [ 'access_token' => 'required|string' // incoming token from provider ]
URL段
-
provider
- 提供者名称。例如:google、facebook等。 -
sociable
- 根据您的配置文件命名的sociable模型名称。例如:user、customer等。
定制化
对于大多数项目,安装后您可能根本不需要做什么。如果您有不同需求,您可以自由调整配置以添加/删除模型和提供者,使用您自己的控制器或甚至实现您自己的数据库逻辑。
定制支持的模型和提供者
您可以支持任何模型进行认证。
- 在配置文件的
sociables
键中添加条目,指示模型类以及您希望为该模型允许的特定提供者。
// config/socialauth.php 'sociables' => [ // default model. You can remove it or tweak it. 'user' => [ 'model' => User::class, 'providers' => [ 'google', 'facebook', 'twitter', ], ], // Customer model example // 'customer' => [ // 'model' => Customer::class, // 'providers' => [ // 'google', // 'github', // ], // ], ],
- 接下来,确保您的模型实现了并使用了以下合约和特质。
// Transforms User profile info from the social account to your sociable model. use Rzb\SocialAuth\Contracts\Sociable as SociableContract; use Rzb\SocialAuth\Traits\Sociable; // Converts your sociable model to its respective JsonResource class. // Only needed if you're using the package's default controller. use Rzb\SocialAuth\Contracts\Resourceable as ResourceableContract; use Rzb\SocialAuth\Traits\Resourceable;
定制路由和控制器
您可以将中间件和路由前缀应用到包的路由上。或者甚至用您自己的控制器替换它。
// config/socialauth.php 'routes' => [ 'controller' => SocialAuthController::class, 'middleware' => null, 'prefix' => 'auth/social', ],
定制数据库逻辑
Sociable
特质涵盖了具有用户名和密码的基本用户模型。如果您的模型具有不同的结构,您可能需要定义自己的createFromSocialUser
方法。
use Laravel\Socialite\Contracts\User as SocialUser; public static function createFromSocialUser(SocialUser $socialUser): self { return self::forceCreate([ // map your model attributes here 'email' => $socialUser->getEmail(), 'name' => $socialUser->getName(), ]); }