Laravel 5.2 通过 API 进行身份验证

Laravel 5.2 Authentication via API

我正在用 Laravel 5.2 开发 RESTful API。在位于第 46 行 \Illuminate\Auth\TokenGuard\TokenGuard.php 的令牌守卫中,令牌的列名称定义为 api_token:

$this->storageKey = 'api_token';

我想将此列名称更改为其他名称,例如 api_key

我该怎么做?我不想修改核心 TokenGuard.php 文件。

内置TokenGuard没有办法修改storageKey字段。因此,您需要创建自己的 Guard class 来设置字段,并告诉 Auth 使用您的 Guard class.

首先,首先创建一个扩展基础 TokenGuard class 的新 Guard class。在此示例中,它创建于 app/Services/Auth/MyTokenGuard.php:

namespace App\Services\Auth;

use Illuminate\Http\Request;
use Illuminate\Auth\TokenGuard;
use Illuminate\Contracts\Auth\UserProvider;

class MyTokenGuard extends TokenGuard
{
    public function __construct(UserProvider $provider, Request $request)
    {
        parent::__construct($provider, $request);
        $this->inputKey = 'api_key'; // if you want to rename this, as well
        $this->storageKey = 'api_key';
    }
}

创建 class 后,您需要让 Auth 知道。您可以在 AuthServiceProvider 服务提供商的 boot() 方法中执行此操作:

public function boot(GateContract $gate)
{
    $this->registerPolicies($gate);

    Auth::extend('mytoken', function($app, $name, array $config) {
        return new \App\Services\Auth\MyTokenGuard(Auth::createUserProvider($config['provider']), $app['request']);
    });
}

最后,您需要告诉 Auth 使用您的新 mytoken 守卫。这是在 config/auth.php 配置文件中完成的。

'guards' => [
    'api' => [
        'driver' => 'mytoken',
        'provider' => 'users',
    ],
],

遗憾的是,无法对其进行配置。

使用其他密钥的唯一方法是创建您自己的密钥 "Guard":Adding Custom Guards

您可以扩展 TokenGuard class 并用您自己的列名覆盖 __constructor