我正在使用Laravel 5.2开发RESTful API。在位于第46行\Illuminate\Auth\TokenGuard\TokenGuard.php
的令牌守卫中,令牌的列名定义为api_token
:
$this->storageKey = 'api_token';
我想将此列名更改为其他名称,例如api_key
。
我该怎么做?我不想修改核心TokenGuard.php
文件。
答案 0 :(得分:16)
内置 function fetch_hash($username, $dbc)
{
$fetch_hash = $dbc->prepare("SELECT * FROM users WHERE username = :username");
$fetch_hash->bindValue(":username", $username);
$fetch_hash->execute();
$result = $fetch_hash->fetchAll();
$hash = $result[0][password];
return $hash;
}
$correct_hash = fetch_hash($username, $dbc);
list($salt, $hash) = explode('.', $correct_hash);
$password = "password";
echo "Generated hash : " . crypt($password, $salt); // Returns *0
echo "Generated hash 2: " . crypt($password, "$2y$12$p7MTIQRBzetIWkH5zeqr5"); // Returns the correct hash which matches the on stored in the database
无法修改TokenGuard
字段。因此,您需要创建自己的storageKey
类来设置字段,并告诉Guard
使用您的Auth
类。
首先,首先创建一个扩展基类Guard
类的新Guard
类。在此示例中,它是在TokenGuard
创建的:
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';
}
}
了解它。您可以使用Auth
服务提供商的boot()
方法执行此操作:
AuthServiceProvider
最后,您需要告诉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
答案 1 :(得分:1)
不幸的是没有办法配置它。
使用其他密钥的唯一方法是创建自己的" Guard":Adding Custom Guards。
您可以扩展TokenGuard
类并使用您自己的列名覆盖__constructor
。