因为你需要更改用户如何检索出的数据库,你实际上需要创建和使用自定义UserProvider
,不是自定义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
知道它。您可以在AuthServiceProvider
服务提供商的boot()
方法中执行此操作。这个例子将使用“myeloquent”这个名字,但你可以使用任何你想要的(除了“雄辩”和“数据库”)。
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,
],
],
您可以阅读更多关于在documentation here中添加自定义用户提供者的信息。
我也有同样的问题。 :( –
这个问题很复杂,如果你可以简单描述它会更好地帮助你.. –
@BasheerAhmedKharoti令牌警卫用于存储令牌存储密钥的列的名称更改 – Katerou22