9

拉拉维尔 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 密钥输入和存储密钥,

我该怎么办?!

谢谢

4

2 回答 2

19

从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',
    ],
],
于 2019-02-27T09:24:18.850 回答
4

因为您需要更改从数据库中检索用户的方式,所以您实际上需要创建和使用 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,
    ],
],

您可以在此处的文档中阅读有关添加自定义用户提供程序的更多信息。

于 2017-09-21T16:43:13.970 回答