Tp6 jwt使用

  • Post author:
  • Post category:其他


1.安装:composer require thans/tp-jwt-auth

2.安装扩展:php think jwt:create

3.生成配置文件与密钥

在这里插入图片描述

4.编写类文件

<?php

namespace app\common\lib\built;

use thans\jwt\facade\JWTAuth;
use thans\jwt\exception\TokenInvalidException;

class Jwt
{
    //刷新token
    public function refreshToken()
    {
        try {
            $result = JWTAuth::refresh();
            return ajaxSuccess([
                'token' => $result,
                'token_expires_time' => $_SERVER['REQUEST_TIME'] + 7000,
            ]);
        } catch (\Throwable $e) {
            return ajaxError('请重新登录' . $e->getMessage(), 'user_error');
        }
    }


    /**
     * 生成token
     * @param $data
     * @return array
     */
    public function createToken(array $data)
    {
        // 生成token
        try {
            $token = JWTAuth::builder($data);
            return ajaxSuccess($token);
        } catch (\Throwable $e) {
            return ajaxError('token创建失败' . $e->getMessage());
        }
    }


    /**
     * 验证token是否有效
     * @return array
     */
    public function checkToken()
    {
        try {
            $result = JWTAuth::auth();
            return ajaxSuccess($result, '验证成功');
        } catch (\Throwable $e) {
            return ajaxError('请先登录', 'user_error');
        } catch (TokenInvalidException $exception) {
            return ajaxError('无效的Token', 'jwt_expire');
        }
    }
}
```php

5.生成token

$JwtImpl = new Jwt();
$result = $JwtImpl->createToken($staff_info);

6.验证token

$JwtImpl = new \app\common\lib\built\Jwt();
$result = $JwtImpl->checkToken();
if ($result['status'] != 1) {
    return json($result);
}

7.刷新token

$JwtClass = new Jwt();
$result = $JwtClass->refreshToken();



版权声明:本文为CS__Love原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。