Kat*_*u22 3 php mysql authentication laravel laravel-5.5
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';
}
Run Code Online (Sandbox Code Playgroud)
现在我想api_key从与用户表的关系中定义如下:
device_user table -> token
Run Code Online (Sandbox Code Playgroud)
我想为用户拥有的每个设备定义特定的令牌,并且我想将api键输入和存储键设置为用户和设备之间数据透视表中的此列,
我该怎么办?
谢谢
从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',
],
],
Run Code Online (Sandbox Code Playgroud)
因为您需要更改从数据库中检索用户的方式,所以您实际上需要创建和使用 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.
}
}
Run Code Online (Sandbox Code Playgroud)
一旦你创建了你的类,你需要让大家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']);
});
}
Run Code Online (Sandbox Code Playgroud)
最后,您需要告知Auth使用新的myeloquent用户提供商。这是在config/auth.php配置文件中完成的。
'providers' => [
'users' => [
'driver' => 'myeloquent', // this is the provider name defined above
'model' => App\User::class,
],
],
Run Code Online (Sandbox Code Playgroud)
您可以在此处的文档中阅读有关添加自定义用户提供程序的更多信息。
| 归档时间: |
|
| 查看次数: |
1870 次 |
| 最近记录: |