• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

借助ThinkPHP6扩展插件JWT-AUTH实现jwt验证

武飞扬头像
y_w_x_k
帮助6

1.环境要求

  1. php ^7.0 || ^8.0
  2. thinkphp ^5.1.10 || ^6.0.0

2.安装插件

  1.  
    composer require thans/tp-jwt-auth
  2.  
     
  3.  
    //此举将生成jwt.php和.env配置文件
  4.  
    php think jwt:create

jwt.php

  1.  
    return [
  2.  
    'secret' => env('JWT_SECRET'),
  3.  
    //Asymmetric key
  4.  
    'public_key' => env('JWT_PUBLIC_KEY'),
  5.  
    'private_key' => env('JWT_PRIVATE_KEY'),
  6.  
    'password' => env('JWT_PASSWORD'),
  7.  
    //JWT time to live
  8.  
    'ttl' => env('JWT_TTL', 15),//token过期时间,方便测试先调整到15秒过期
  9.  
    //Refresh time to live
  10.  
    'refresh_ttl' => env('JWT_REFRESH_TTL', 1), //单位分钟,指定token过期后,多长一段时间内,使用过期的token能够刷新,最好自动刷新,刷新后会在header里面返回,注意保存
  11.  
    //JWT hashing algorithm
  12.  
    'algo' => env('JWT_ALGO', 'HS256'),
  13.  
    'token_mode' =>['header', 'cookie', 'param'],
  14.  
     
  15.  
    'blacklist_storage' => thans\jwt\provider\storage\Tp5::class,
  16.  
    ];
学新通

.env

  1.  
    APP_DEBUG = true
  2.  
     
  3.  
    [JWT]
  4.  
    SECRET=ecaff98fa0d92f8abdcc8e1eee590bb4
  5.  
    TTL=20

3.配置中间件

  1.  
    // 中间件配置
  2.  
    return [
  3.  
    // 别名或分组
  4.  
    'alias' => [
  5.  
    'jwtAuth' => \thans\jwt\middleware\JWTAuth::class,
  6.  
    /**
  7.  
    * JWTAuthAndRefresh包含jwt验证和token自动刷新的功能,所以一般只需要引入该中间件即可
  8.  
    * jwt自动刷新后会返回新的token,所以需要前端判断是否接收到header的Authorization,有值则保存新的token
  9.  
    */
  10.  
    'autoRefreshJwt' => \thans\jwt\middleware\JWTAuthAndRefresh::class
  11.  
    ],
  12.  
    ];

4.调用

  1.  
    use app\BaseController;
  2.  
    use thans\jwt\facade\JWTAuth;
  3.  
     
  4.  
    class Hello extends BaseController
  5.  
    {
  6.  
    protected $middleware = ['autoRefreshJwt'];
  7.  
    public function testJwt():void{
  8.  
    $tokenStr = JWTAuth::getToken();
  9.  
    echo $tokenStr;
  10.  
    }
  11.  
    }

完成!

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhffhjeh
系列文章
更多 icon
同类精品
更多 icon
继续加载