Home  >  Article  >  PHP Framework  >  ThinkPHP5-Deploy JWT using think-API

ThinkPHP5-Deploy JWT using think-API

藏色散人
藏色散人forward
2019-09-12 10:56:473477browse

Because the next project will use TP5 to develop a small program, so I used the TP framework. Because small program development requires a background to write the api interface, I checked online to see if there are any related dependencies. I recommend it here. think-api extension tool, because I mainly want to use the jwt function to determine the login status of the mini program user. Let's take my project as an example and briefly talk to you about deploying JWT through think-api.

1. Installation dependencies

The TP version I use is TP5.1, the extension download address is: https://github.com/czewail/think-api, Install dependencies through composer:

$ composer require zewail/think-api:1.1.x

2. Configuration instructions

After the extension is installed, we can view it in the vendor/think-api/config/jwt.php file jwt configuration.

Mainly the user model path needs to be modified:

return [
    // 加密算法
    'algorithm'      => 'HS256',
    // HMAC算法使用的加密字符串
    'key'            => 'ex-key',
    // RSA算法使用的私钥文件路径
    'privateKeyPath' => '/home/rsa_private_key.pem',
    // RSA算法使用的公钥文件路径
    'publicKeyPath'  => '/home/rsa_public_key.pem',
    // 误差时间,单位秒
    'deviation'      => 60,
    // 过期时间, 单位分钟
    'ttl'            => 120,
    // 用户模型路径
    'user'           => app\api\model\User::class,
];

3. Create an API interface controller

Create what we want through the command line To return the Token to the front-end controller

$ php thnk make:controller api/Index

4. Reference dependency

Add the file path in the created file header: use Zewail\Api\Facades\JWT; The case code is as follows:

public function index()
    {
        //获取前台发送过来的登录信息
        $tel      = $this->request->tel;
        $password = $this->request->passwword;
        //把登录信息传入JWT验证匹配
        $credentials = ['tel' => $tel, 'password' => $password];
        //1.验证通过返回token  1和2任意取一种方式
        $token = JWT::attempt($credentials);
        //2.通过已有账户模型生成token  1和2任意取一种方式
        $user  = User::find(84);
        $token = JWT::fromUser($user);
        $msg   = "验证成功";
        //把token发送给前台确认是否成功登陆
        return $this->ApiSuccess($token, $msg);
    }

One thing to note is that the API’s default receiving parameters are mobile and password. In the door-to-door example, these are tel and password. The variable name has been changed, so we need to insert some code into the user model to illustrate. And so on.

public $jwtSub = 'tel';

5. Configure routing

在 route/route.php 中加入路由地址 Route::get('api/test', 'api/Index/index');

6. Run test

The test results in postman are as follows, so we can The token can be generated in the background and returned to the front desk for verification and login.

ThinkPHP5-Deploy JWT using think-API

7. Verification token (supplementary)

We resend the previously generated token in postman with the header included. Go to the backend to perform token verification, as shown in the figure below.

ThinkPHP5-Deploy JWT using think-API

Then carry the header to access the verification route. The verification code is as follows:

       if ($user = JWT::authenticate()) {
                return true;
        }

If the verification is correct, true will be returned.

8. Regarding the problem of token non-existence and token expiration (supplementary)

In the vendor\think-api\src\JWT/Factories\code.php file The think-api interface provides us with corresponding error feedback.

// 检查是否过期
if (isset($payload->exp) && (time() - $this->deviation) >= $payload->exp) {
    throw new TokenExpiredException('该 Token 已过期');
}
// 验证签名
if (!$this->verify("$header64.$payload64", $signature)) {
    throw new TokenInvalidException('无效的 Token');
}

So how do we use these status feedbacks? This requires using front-end middleware to verify the token information sent by the front end.

First create the middleware:

$ php think make:middle Test

Then write the following content in the middleware:

  //用try catch捕获报错反馈
    public function handle($request, Closure $next)
    {
        try {
            if (!$user = JWT::authenticate()) {
                return response()->json([
                    'errcode' => 1004,
                    'errmsg'  => '无此用户',
                ], 404);
            }
            return $next($request);
        } catch (TokenExpiredException $e) {
            return response()->json([
                'errcode' => 1003,
                'errmsg'  => 'token 过期', //token已过期
            ]);
        } catch (TokenInvalidException $e) {
            return response()->json([
                'errcode' => 1002,
                'errmsg'  => 'token 无效', //token无效
            ]);
        } catch (JWTException $e) {
            return response()->json([
                'errcode' => 1001,
                'errmsg'  => '缺少token', //token为空
            ]);
        }
    }

Then just reference it in the route.

Recommended tutorial: thinkphp tutorial

The above is the detailed content of ThinkPHP5-Deploy JWT using think-API. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete