通过API的Laravel 5.2身份验证 [英] Laravel 5.2 Authentication via API

查看:95
本文介绍了通过API的Laravel 5.2身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 5.2开发RESTful API.在第46行\Illuminate\Auth\TokenGuard\TokenGuard.php上的令牌保护中,令牌的列名称定义为api_token:

I am developing a RESTful API with Laravel 5.2. In the token guard located at \Illuminate\Auth\TokenGuard\TokenGuard.php on line 46 the column name for the token is defined as api_token:

$this->storageKey = 'api_token';

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

I want to change this column name to something else, for example api_key.

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

How can I do this? I do not want to modify the core TokenGuard.php file.

推荐答案

内置的TokenGuard无法修改storageKey字段.因此,您将需要创建自己的用于设置字段的Guard类,并告诉Auth使用您的Guard类.

The built in TokenGuard does not have a way to modify the storageKey field. Therefore, you will need to create your own Guard class that sets the field, and tell Auth to use your Guard class.

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

First, start by creating a new Guard class that extends the base TokenGuard class. In this example, it is created at 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知道它.您可以在AuthServiceProvider服务提供商的boot()方法中执行此操作:

Once you've created your class, you need to let Auth know about it. You can do this in the boot() method on your AuthServiceProvider service provider:

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配置文件中完成的.

And finally, you need to tell Auth to use your new mytoken guard. This is done in the config/auth.php config file.

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

这篇关于通过API的Laravel 5.2身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆