因为您需要更改从数据库中检索用户的方式,所以您实际上需要创建和使用 custom UserProvider
,而不是 custom Guard
。如果您想将输入键或存储键从api_token
.
因此,您需要一个新的自定义UserProvider
类,该类知道如何使用给定的凭据(令牌)检索您的用户,并且您需要告诉Auth
您使用新的自定义UserProvider
类。
首先,假设您仍在使用 Eloquent,首先创建一个UserProvider
扩展基类的新EloquentUserProvider
类。在此示例中,它创建于app/Services/Auth/MyEloquentUserProvider.php
。在此类中,您将需要retrieveByCredentials
使用有关如何使用提供的令牌检索用户的详细信息来覆盖该函数。
namespace App\Services\Auth;
use Illuminate\Auth\EloquentUserProvider;
class MyEloquentUserProvider extends EloquentUserProvider
{
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials)) {
return;
}
// $credentials will be an array that looks like:
// [
// 'api_token' => 'token-value',
// ]
// $this->createModel() will give you a new instance of the class
// defined as the model in the auth config for your application.
// Your logic to find the user with the given token goes here.
// Return found user or null if not found.
}
}
创建类后,您需要Auth
告知它。您可以在服务提供商的boot()
方法中执行此操作。AuthServiceProvider
此示例将使用名称“myeloquent”,但您可以使用任何您想要的名称(“eloquent”和“database”除外)。
public function boot()
{
$this->registerPolicies();
Auth::provider('myeloquent', function($app, array $config) {
return new \App\Services\Auth\MyEloquentUserProvider($app['hash'], $config['model']);
});
}
最后,您需要告诉Auth
使用您的新myeloquent
用户提供程序。这是在config/auth.php
配置文件中完成的。
'providers' => [
'users' => [
'driver' => 'myeloquent', // this is the provider name defined above
'model' => App\User::class,
],
],
您可以在此处的文档中阅读有关添加自定义用户提供程序的更多信息。