菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
93
0

Hyperf 下 http 认证组件

原创
05/13 14:22
阅读数 336

 Hyperf 下 http 认证组件

- 仿照 laravel auth 组件, 抽离出其中的核心组件, 形成当前扩展包

- 将 UserProvider 与 Guard 抽离出去, 形成单独扩展包, 方便扩展, 默认使用以下组合

    * fx/eloquent-provider 使用 Eloquent ORM ;

    * fx/session-guard 使用 session 作为 guard ;

 使用

 安装

composer require fx/hyperf-http-auth

 发布配置文件

php bin/hyperf.php vendor:publish fx/hyperf-http-auth

 创建用户 model 并修改为以下配置

<?php
declare (strict_types=1);
namespace App\Model;

use Fx\HyperfHttpAuth\Contract\Authenticatable;
use Hyperf\DbConnection\Model\Model;
class User extends Model implements Authenticatable
{
    use Fx\HyperfHttpAuth\Authenticatable;
}

 配置依赖扩展

fx/session-guard 依赖 hyperf/session 需要正确配置其相关内容 官方文档

 在 controller 中使用

<?php
declare(strict_types=1);
namespace App\Controller;

use App\Model\User;
use Fx\HyperfHttpAuth\Contract\HttpAuthContract;
use Hyperf\Di\Annotation\Inject;
class IndexController extends AbstractController
{

    /**
     * @Inject()
     * @var HttpAuthContract
     */
    protected $auth;

    public function index()
    {
        return $this->data();
    }

    /**
     * 登录
     */
    public function login()
    {
        /** 方式 1 */
        // 等价于 auth()->login(User::first());
        $this->auth->login(User::first());

        /** 方式 2 */
        // 等价于 auth()->attempt(['email' => 'xxx', 'password' => '123456']);
        $this->auth->attempt(['email' => 'xxx', 'password' => '123456']);

        return $this->data();
    }

    /**
     * 登出
     */
    public function logout()
    {
        // 等价于 auth()->logout();
        $this->auth->logout();
        return $this->data();
    }

    protected function data()
    {
        return [
            'user' => auth()->user(),
            'is_login' => auth()->check(),
        ];
    }
}

 扩展 UserProvider

- 实现 Fx\HyperfHttpAuth\Contract\UserProvider 这个抽象类

- 添加 Fx\HyperfHttpAuth\Annotation\UserProviderAnnotation 类注解, 该注解接收一个参数, 为该驱动的名称

- 可参考: fx/eloquent-provider

 扩展 Guard

- 实现 Fx\HyperfHttpAuth\Contract\StatefulGuard 这个抽象类

- 添加 Fx\HyperfHttpAuth\Annotation\GuardAnnotation 类注解, 该注解接收一个参数, 为该驱动的名称

- 可参考: fx/session-guard

发表评论

0/200
93 点赞
0 评论
收藏
为你推荐 换一批