Laravel 使用第三方身份验证的身份验证

Laravel Auth using Third Party Authentication

我正在构建一个使用第三方身份验证数据库的应用程序。我有 created a custom composer package 到 "intercept" POST/login 的请求。一切正常 - 我能够取回用户对象并将其保存到我的 (laravel) 数据库中。

我现在想要重定向到主页并执行 "stuff"。如果可以的话,我想尽可能地使用Laravel的原生Auth

比如在首页我是这样做的:

$foo = auth()->user()->foo->where('active', 1);

毫不奇怪,因为我没有使用 Laravel 的本机 Auth 方法,auth()->user() 正在返回 null。一旦我的数据库中有了我的用户 created/found,是否可以绑定回 Laravel 的 auth() 方法?

感谢您的任何建议!

编辑

阅读文档,this looks like the direction I need to go 但我对如何 connect/register 我的自定义包(我认为)...

了解不多

编辑 2

我会继续更新这个,因为我觉得我取得了任何进展,希望它不仅能帮助我,还能帮助其他人更好地了解我正在努力完成的事情。最终帮助可能正在尝试做同样事情的其他人。

我已经更新了我的app/Providers/AuthServiceProviderAuthServiceProvider

use My\Package\MyThirdPartyServiceProvider;


...


Auth::provider('foo', function ($app, array $config) {
        // Return an instance of Illuminate\Contracts\Auth\UserProvider...

    return new MyThirdPartyServiceProvider($app->make('foo.connection'));
});

我也更新了我的 config/auth 文件:

'providers' => [
    'users' => [
        'driver' => 'foo',
        'model' => App\User::class,
    ]

如您所述,documentation 建议实施自定义用户提供程序。以下步骤或多或少地描述了您将如何更详细地解决它。

  1. 创建或编辑 service provider 您可以通过 运行
  2. 创建新的服务提供商

php artisan make:provider CustomAuthServiceProvider

  1. 在您的服务提供商的 boot 方法中,您必须配置我们的身份验证提供商(将在第 4 步中实现)。
    public function boot()
    {
        Auth::provider('custom-auth', function ($app, array $config) {
            return new CustomAuthProvider();
        });
    }
  1. 更新您的 auth.php 配置以使用我们在第 2 步中注册的服务提供商
'providers' => [
    'users' => [
        'driver' => 'custom-auth',
    ],
],
  1. 创建 CustomAuthProvider class 本身并实现 UserProvider interface
class CustomAuthProvider implements UserProvider
{
    public function retrieveById($identifier) {
        // Retrieve a user by their unique identifier.
    }

    public function retrieveByToken($identifier, $token) {
        // Retrieve a user by their unique identifier and "remember me" token.
    }

    public function updateRememberToken(Authenticatable $user, $token) {
        // Update the "remember me" token for the given user in storage.
    }

    public function retrieveByCredentials(array $credentials) {
        // Retrieve a user by the given credentials.
    }

    public function validateCredentials(Authenticatable $user, array $credentials) {
        // Validate a user against the given credentials.
    }
}