通过自定义认证器,实现自定义token登录验证
因为是简单的自用项目,感觉用jwt有点太重了,所以有了这个自定义token登录验证
在AuthServiceProvider
自定义认证器
public function boot()
{
$this->registerPolicies();
Auth::extend('openApi', function ($app) {
return new ApiGuard($app['request']);
});
}
在auth.php配置文件的guards 配置中的驱动程序
'guards' => [
'openApi' => [
'driver' => 'openApi',
'provider' => 'users',
],
],
创建认证器类
<?php
namespace App\Guards;
use App\Models\User;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\GuardHelpers;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class ApiGuard implements Guard
{
use GuardHelpers;
protected $app;
protected $request;
protected $inputKey;//表单值
public function __construct(Request $request)
{
$this->request = $request;
$this->inputKey = 'access_token';
}
/**
* Get the currently authenticated user.
*
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function user()
{
if(!is_null($this->user)){
return $this->user;
}
$apiToken = $this->getApiToken();
return $this->user = $apiToken;
}
public function getApiToken()
{
$token=$this->getRequestToken();
return $this->checkToken($token);
}
public function checkToken($token){
$user_id = Cache::get('apiToken:'.$token);
if (!$user_id) {
throw new AuthenticationException('token已过期,请从新登录');
}
$user = User::getUser($user_id);
if ($user) {
return $user;
}
throw new AuthenticationException('账号不存在');
}
public function getRequestToken()
{
$token = $this->request->query($this->inputKey);
if (empty($token)) {
$token = $this->request->bearerToken();
}
if (! empty($token)) {
return $token;
}
throw new AuthenticationException('缺少AccessToken值');
}
/**
* Validate a user's credentials.
* @param array $credentials
* @return bool
*/
public function validate(array $credentials = [])
{
if ($this->checkToken($credentials['access_token'])) {
return true;
}
return false;
}
}
获取用户信息
/**
* @param int $user_id
* @return mixed
*/
public static function getUser(int $user_id, string $obj='')
{
$user = Cache::remember('user:'.$user_id, 86400, function () use($user_id) {
return User::query()->where(['id'=>$user_id])->select(['id','name','avatar','role_id'])->first();
});
if($user && $obj){
return $user->toArray();
}
return $user;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
JWT还重?不要重复造轮子