Laravel5.3 使用默认api验证登陆 (4056 views)

不耳

2017-01-23 16:22:33

讲解如何使用laravel5.3框架默认的api验证登陆。

讲道理

config/auth.php里,默认guard有web和api

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],

框架自带有2个guard,在Illuminate\Auth\AuthManager里定义的。此类有2个方法:

public function createSessionDriver($name, $config) {...}
public function createTokenDriver($name, $config) {...}

分别调用SessionGuard和TokenGuard,由resolve($name)方法来调用。

配置文件中的driver填token,既是使用 Illuminate\Auth\TokenGuard,打开此文件,可以看到默认的token验证字段名是api_token

public function __construct(UserProvider $provider, Request $request)
{
    $this->request = $request;
    $this->provider = $provider;
    $this->inputKey = 'api_token';
    $this->storageKey = 'api_token';
}

开始

数据库中添加字段不重复字段:api_token

$table->string('api_token', 60)->unique();

登陆验证: 验证了用户名和密码之后,生成一个api_token,填到数据库里。然后就可以使用token来访问需要登陆的页面了。 使用Auth门面调用guard,使用validate()方法验证身份:(返回bool)

Auth::guard('api')->validate(['api_token' => $request->input('myApiToken')]);

user()方法返回用户信息

Auth::guard('api')->user();

等等,具体查看Illuminate\Auth\TokenGuard类。 测试的话,直接使用get请求就行了:

http://xxx.com/user?api_token=xxxxxxxxxx