记一次Laravel JWT自定义UserProvider修改认
一个微信小程序的项目打算用Laravel+JWT来开发接口,用户通过微信登录成功后把
open_id
保存下来,生成一个token返回给用户。通过token来认证,起到保护open_id
的作用。
JWTAuth::attempt(['open_id'=>'*****4vyXJN-Fv-5r9pbW3l****']);
把官方的范例改成使用open_id
认证时出现了问题:
查看auth配置:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
jwt使用的是provider是eloquent,即 Illuminate\Auth\EloquentUserProvider
查看代码发现,其中的validateCredentials
方法指定了必须使用密码登录
/**
* Validate a user against the given credentials.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param array $credentials
* @return bool
*/
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
于是想到自定义一个UserProvider来代替eloquent。
这个Provider只要实现Illuminate\Contracts\Auth\UserProvider
接口就好,也可以直接继承Illuminate\Auth\EloquentUserProvider
。
但由于 Illuminate\Auth\EloquentUserProvider
的构造方法有两个参数,其中的一个参数Illuminate\Contracts\Hashing\Hasher
我用不到,所以还是亲自实现接口吧。
把其他方法都复制过来,然后改写validateCredentials
方法使用open_id
来进行认证。
<?php
namespace App\Api\Provider;
use Illuminate\Auth\EloquentUserProvider;
class MyEloquentProvider extends EloquentUserProvider{
/**
* Validate a user against the given credentials.
*
* @param \App\Api\Contract\WeixinAuthenticatable $user
* @param array $credentials
* @return bool
*/
public function validateCredentials(Authenticatable $user, array $credentials)
{
$plain = $credentials['open_id'];
return $this->check($plain, $user->findOpenId());
}
protected function check($plain, $open_id)
{
return $plain === $open_id;
}
}
接下来我在
AuthServiceProvider
中注册自己的UserProvider
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
Auth::provider('weixin', function($app, $config){
return new EloquentUserProvider(config('auth.providers.users.model'));
});
}
在配置中新加入一个provider,并将api的provider指向新加入的provider:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'weixin',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
'weixin' => [
'driver' => 'weixin',
'model' => App\User::class,
],
],
但是测试依然提示我 Undefined index: password 显然JWTAuth门面并没有走我刚刚自定义的UserProvider,这是为什么呢?
我打印了堆栈信息后发现,程序先走到了Illuminate\Http
的user
方法,然后调用自身的userResolver
绑定的方法来解析用户。
/**
* Get the user making the request.
*
* @param string|null $guard
* @return mixed
*/
public function user($guard = null)
{
return call_user_func($this->getUserResolver(), $guard);
}
/**
* Get the user resolver callback.
*
* @return \Closure
*/
public function getUserResolver()
{
return $this->userResolver ?: function () {
//
};
}
而这里的userResolver
实际上是指向Illuminate\Auth\AuthManager
中绑定的userResolver
方法
/**
* The user resolver shared by various services.
*
* Determines the default user for Gate, Request, and the Authenticatable contract.
*
* @var \Closure
*/
protected $userResolver;
/**
* Create a new Auth manager instance.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function __construct($app)
{
$this->app = $app;
$this->userResolver = function ($guard = null) {
return $this->guard($guard)->user();
};
}
/**
* Attempt to get the guard from the local cache.
*
* @param string $name
* @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard
*/
public function guard($name = null)
{
$name = $name ?: $this->getDefaultDriver();
return $this->guards[$name] ?? $this->guards[$name] = $this->resolve($name);
}
/**
* Get the default authentication driver name.
*
* @return string
*/
public function getDefaultDriver()
{
return $this->app['config']['auth.defaults.guard'];
}
这里的$guards[$name]
实际上我们并没有传值,所以程序走到了getDefaultDriver
中,获取到的是auth中的defaults配置,而defaults中guard的配置是web
。我将defaults中的guard改为api后,果然认证就成功了。
第一次尝试laravel框架,第一次使用JWT组件,果然就一脚踏入了一个大坑。趟平这个坑废了不少的精力和时间,但也算彻底搞清了JWT中的一些问题。
比如:JWTAuth
门面实际上返回的是Tymon\JWTAuth\JWTAuth
,而auth
辅助方法返回的却是我们auth配置中的guard。
所以如果不想修改defaults配置又想使用自定义provider的话,可以使用辅助函数:
auth('weixin')->attempt(['open_id'=>'*****4vyXJN-Fv-5r9pbW3l****']);