通过自定义认证器,实现自定义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 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 1

JWT还重?不要重复造轮子

7个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!