如何更改令牌保护中的api_token列

问题描述 投票:2回答:2

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

我应该怎么做?!

谢谢

php mysql laravel authentication laravel-5.5
2个回答
4
投票

因为您需要更改用户从数据库中检索的方式,您实际上需要创建和使用自定义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中阅读有关添加自定义用户提供程序的更多信息。


5
投票

自版本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',
    ],
],
© www.soinside.com 2019 - 2024. All rights reserved.