Home > PHP Framework > ThinkPHP > body text

ThinkPHP5-Deploy JWT using think-API

藏色散人
Release: 2019-09-30 18:09:30
forward
3461 people have browsed it

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
Copy after login

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,
];
Copy after login

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
Copy after login

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);
    }
Copy after login

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';
Copy after login

5. Configure routing

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

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;
        }
Copy after login

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');
}
Copy after login

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
Copy after login

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为空
            ]);
        }
    }
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template