Laravel 5.5
我想改变在TokenGaurd中使用的api令牌的方向,所以,我创建了一个名为CafeTokenGaurd的自定义防护扩展TokenGuard,我将__construct函数定义为我想要的东西,如下所示:
public function __construct(UserProvider $provider, Request $request) {
parent::__construct($provider, $request);
$this->inputKey = 'api_key'; // I want changing this part
$this->storageKey = 'api_key';
}
现在我想从与用户表的关系定义api_key
,如下所示:
device_user table -> token
我想为用户拥有的每个设备定义特定的令牌,我想在用户和设备之间的数据透视表中为此列设置api密钥输入和存储密钥,
我应该怎么做?!
谢谢
因为您需要更改用户从数据库中检索的方式,您实际上需要创建和使用自定义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
了解它。您可以在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,
],
],
您可以在documentation here中阅读有关添加自定义用户提供程序的更多信息。
自版本Laravel 5.7.28,你可以简单地设置在config/auth.php
。
'guards' => [
'api' => [
'driver' => 'token',
'input_key' => 'token', // The input name to pass through
'storage_key' => 'token', // The column name to store in database
'provider' => 'users',
],
],