2017-09-20 31 views
1

Laravel 5.5如何改变api_token列令牌后卫

我想改变,在使用TokenGaurd所以, 我创建了一个名为CafeTokenGaurd定制后卫延伸TokenGuard API令牌的方向,我定义__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键输入和存储键可在用户和设备间的数据透视表此列,

我应该如何这个?!

感谢

+1

我也有同样的问题。 :( –

+0

这个问题很复杂,如果你可以简单描述它会更好地帮助你.. –

+0

@BasheerAhmedKharoti令牌警卫用于存储令牌存储密钥的列的名称更改 – Katerou22

回答

3

因为你需要更改用户如何检索出的数据库,你实际上需要创建和使用自定义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中添加自定义用户提供者的信息。

+0

所以在这个阵列[ “api_token” =>“令牌值”, ]如何我可以定义$ user-> devices实例?我的API令牌是在设备和用户之间的枢纽这就是我的问题 – Katerou22

+1

@ Katerou22这个想法是,你有你的'标记值'。现在您需要查找属于该令牌的用户。我不知道你的模型名称或关系,但是你可能在'retrieveByCredentials()'方法内寻找类似的东西:'$ user = $ this-> createModel() - > newQuery() - > whereHas 'devices',function($ query)use($ credentials){return $ query-> where('device_user.token',$ credentials ['api_token']);}) - > first();'理论上,具有相匹配令牌的相关设备的用户。 – patricus

+1

你真棒你知道吗?! (我还没有测试过) – Katerou22