tp6 uses middleware to verify token

Token verification function generation: TP6 JWT Token generation controller uses middleware to use_Bug_Free_'s blog-CSDN Blog

0x01 Quickly generate middleware through command line instructions

php think make:middleware CheckToken

This command will  app/middlewaregenerate a middleware under the directory Check.

<?php
 
namespace app\middleware;
 
class CheckToken
{
    public function handle($request, \Closure $next)
    {
        if ($request->param('name') == 'think') {
            return redirect('index/think');
        }
 
        return $next($request);
    }
}

The entry execution method of middleware must be handlea method, and the first parameter is Requestan object, and the second parameter is a closure.

Modify the above fileapp/middleware/CheckToken.php

<?php
 
declare(strict_types=1);
 
namespace app\middleware;
 
// 数据库
use app\model\Admins;
 
class CheckToken
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 获取token
        $token = $request->header('token');
        // 验证是否存在token
        if (empty($token)) {
            return json(['msg' => 'error', 'data' => 'token为空']);
        } else {
            $admins_token =  Admins::where('token', $token)->find();
            // JWT进行校验token
            $res = checkToken($token);
            // token是否存在数据库中
            if (empty($admins_token)) {
                return json(['msg' => 'error', 'data' => 'token不合法']);
                // token是否正确
                if ($res['code'] != 1) {
                    return json(['msg' => 'error', 'data' => 'token验证失败']);
                }
            }
        }
 
        return $next($request); //返回请求数据本身
    }
}

0x02 Controller middleware use 

['except' => 'login']] can exclude functions that do not need to verify token 

    protected $middleware = [\app\middleware\CheckToken::class => ['except' => 'login']];

0x03 If the verification token middleware is applied globally

In the \app\middleware.php file add

<?php
// 全局中间件定义文件
return [
    // 全局请求缓存
    // \think\middleware\CheckRequestCache::class,
    // 多语言加载
    // \think\middleware\LoadLangPack::class,
    // Session初始化
    // \think\middleware\SessionInit::class
    // 注册中间件
    \app\middleware\CheckToken::class
    // 跨域
    // \think\middleware\AllowCrossDomain::class
];

0x04 If you need to receive token across domains

TP6 middleware opens cross-domain token_Bug_Free_'s blog-CSDN Blog

Guess you like

Origin blog.csdn.net/qq_43929048/article/details/123705415