hyperf2.1+96qbhy/hyperf-auth组件安装使用

2023-06-01 00:00:00 Hyperf hyperf2 qbhy

我有个项目打算用jwt,在找轮子中找到了这个,感觉很便捷,后面打算用,所以测试记录一下

直接按git上的步骤走


我的测试环境介绍:

hyperf2.1 (还没升级比较懒)


因为我到项目在线上跑,所以要先停一下,进入步骤:

[[email protected] ~]# netstat -anp | grep 9501
tcp        0      0 0.0.0.0:9501            0.0.0.0:*               LISTEN      2793/skeleton.Maste 
tcp        0      0 192.168.1.98:9501       192.168.1.38:47904      TIME_WAIT   -                   
[[email protected] ~]# kill -9 2793


进入项目目录开始安装组件

[[email protected] ~]# cd /home/www/hyperf-skeleton/
[r[email protected] hyperf-skeleton]# composer require 96qbhy/hyperf-auth
Using version ^2.4 for 96qbhy/hyperf-auth
./composer.json has been updated
Running composer update 96qbhy/hyperf-auth
Loading composer repositories with package information
Updating dependencies
Lock file operations: 3 installs, 0 updates, 0 removals
  - Locking 96qbhy/hyperf-auth (v2.4.3)
  - Locking 96qbhy/simple-jwt (v1.3.1)
  - Locking doctrine/cache (1.12.1)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 3 installs, 0 updates, 0 removals
As there is no 'unzip' command installed zip files are being unpacked using the PHP zip extension.
This may cause invalid reports of corrupted archives. Besides, any UNIX permissions (e.g. executable) defined in the archives will be lost.
Installing 'unzip' may remediate them.
  - Downloading doctrine/cache (1.12.1)
  - Downloading 96qbhy/simple-jwt (v1.3.1)
  - Downloading 96qbhy/hyperf-auth (v2.4.3)
  - Installing doctrine/cache (1.12.1): Extracting archive
  - Installing 96qbhy/simple-jwt (v1.3.1): Extracting archive
  - Installing 96qbhy/hyperf-auth (v2.4.3): Extracting archive
1 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating optimized autoload files
> rm -rf runtime/container
74 packages you are using are looking for funding.
Use the `composer fund` command to find out more!


生成auth配置文件 (因为是测试我直接在phpstorm批量搜索users 然后用admin替换之)

[[email protected] hyperf-skeleton]# php bin/hyperf.php vendor:publish 96qbhy/hyperf-auth
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Config\Listener\RegisterPropertyHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Paginator\Listener\PageResolverListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\ExceptionHandler\Listener\ExceptionHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\DbConnection\Listener\RegisterConnectionResolverListener listener.
[96qbhy/hyperf-auth] publishes [auth] successfully.

代码就不帖了


生成env中auth信息

[[email protected] hyperf-skeleton]# php bin/hyperf.php gen:auth-env
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Config\Listener\RegisterPropertyHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Paginator\Listener\PageResolverListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\ExceptionHandler\Listener\ExceptionHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\DbConnection\Listener\RegisterConnectionResolverListener listener.
AUTH_SSO_CLIENTS 已生成!
SSO_JWT_SECRET 已生成!
SIMPLE_JWT_SECRET 已生成!

.env代码信息
AUTH_SSO_CLIENTS=h5,weapp
SSO_JWT_SECRET=OxZca6IHFJjH6E2g
SIMPLE_JWT_SECRET=yRQWfCXW5LAty90c



添加登录验证中间件 (注意:有个点的)

php ./bin/hyperf.php gen:middleware Auth
生成中间件文件:\hyperf\app\Middleware\Auth.php


创建mode文件 : \hyperf\app\Model\Admin.php


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

use Hyperf\DbConnection\Model\Model;

use Qbhy\HyperfAuth\Authenticatable;

class Admin extends Model implements Authenticatable
{
    protected $table = 'admin';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
    protected $dates = ['created_at', 'updated_at'];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [];



创建控制器

生成token,删除token,刷新token等操作

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

use App\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\GetMapping;
use Qbhy\HyperfAuth\Annotation\Auth;
use Qbhy\HyperfAuth\AuthManager;

use App\Model\Admin;

/**
 * @Controller()
 */
class AdminController extends AbstractController
{
    /**
     * @Inject
     * @var AuthManager
     */
    protected $auth;
   
    /**
     * @GetMapping(path="/admin/login")
     * @return array
     */
    public function login()
    {
        $user = Admin::query()->where('name','admin')->where('password',123456)->first();
        // auth('guard') || auth()->guard('session'); 不设置guard,则使用默认的配置jwt
        $token = auth()->login($user);
        return [
            'token' => $token,
            'date' => date('Y-m-d H:i:s')
        ];
    }
   
    /**
     * 使用 Auth 注解可以保证该方法必须通过某个 guard 的授权,支持同时传多个 guard,不传参数使用默认 guard
     * @Auth("jwt")
     * @GetMapping(path="/admin/user")
     * @return string
     */
    public function user()
    {
        $user = auth()->user();
        return $user;
    }
   
    /**
     * 退出登录,token失效
     * @Auth("jwt")
     * @GetMapping(path="/admin/logout")
     */
    public function logout()
    {
        auth()->logout();
        return 'logout ok';
    }
   
    /**
     * 刷新token,旧token就会失效
     * @Auth("jwt")
     * @GetMapping(path="/admin/retrieve")
     */
    public function retrieve()
    {
        $token = auth()->refresh();
        return [
            'token' => $token,
            'date' => date('Y-m-d H:i:s')
        ];
    }
}


来几张效果图:

用户信息,已经登录了(已拿到token情况)

用户信息.png

刷新tk

刷新tk.png

相关文章