Home >PHP Framework >ThinkPHP >Detailed example of thinkphp6 using jwt authentication

Detailed example of thinkphp6 using jwt authentication

WBOY
WBOYforward
2022-06-24 12:57:124596browse

This article brings you relevant knowledge about thinkphp, which mainly introduces the issues of using jwt authentication. Let’s take a look at it together. I hope it will be helpful to everyone.

Detailed example of thinkphp6 using jwt authentication

Recommended study: "PHP Video Tutorial"

thinkphp6 Using jwt

  1. The client uses the username and password to request login
  2. The server receives the request and verifies the username and password
  3. After successful verification, the server will issue a token and return the token to the client
  4. After receiving the token, the client can store it, such as putting it in a cookie.
  5. The client needs to carry the token issued by the server every time it requests resources from the server. This can be in a cookie or The header carries
  6. The server receives the request, and then verifies the token contained in the client request. If the verification is successful, it returns the request data to the client

Install jwt extension

composer require firebase/php-jwt

After installation, go to the firebase folder in the vender directory

Detailed example of thinkphp6 using jwt authentication

Call the encode and decode methods in JWT to generate tokens and verify tokens

The common.php global file in the project app directory is used and made into a public method. Since I have multiple applications, I wrote it in the common.php under the api. You can adjust it appropriately according to your own needs

Detailed example of thinkphp6 using jwt authentication

First introduce JWT, and then write two methods to generate signature verification and verification tokens.

<?phpuse  \Firebase\JWT\JWT;use Firebase\JWT\Key;// 应用公共文件/**
 * 生成验签
 * @param $uid 用户id
 * @return mixed
 */function signToken($uid){
    $key=&#39;abcdefg&#39;;         //自定义的一个随机字串用户于加密中常用的 盐  salt
    $token=array(
        "iss"=>$key,        //签发者 可以为空
        "aud"=>'',          //面象的用户,可以为空
        "iat"=>time(),      //签发时间
        "nbf"=>time(),      //在什么时候jwt开始生效
        "exp"=> time()+30,  //token 过期时间
        "data"=>[           //记录的uid的信息
            'uid'=>$uid,
        ]
    );
    $jwt = JWT::encode($token, $key, "HS256");  //生成了 token
    return $jwt;}/**
 * 验证token
 * @param $token
 * @return array|int[]
 */function checkToken($token){
    $key='abcdefg';     //自定义的一个随机字串用户于加密中常用的 盐  salt
    $res['status'] = false;
    try {
        JWT::$leeway    = 60;//当前时间减去60,把时间留点余地
        $decoded        = JWT::decode($token, new Key($key, 'HS256')); //HS256方式,这里要和签发的时候对应
        $arr            = (array)$decoded;
        $res['status']  = 200;
        $res['data']    =(array)$arr['data'];
        return $res;

    } catch(\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
        $res['info']    = "签名不正确";
        return $res;
    }catch(\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
        $res['info']    = "token失效";
        return $res;
    }catch(\Firebase\JWT\ExpiredException $e) { // token过期
        $res['info']    = "token过期";
        return $res;
    }catch(Exception $e) { //其他错误
        $res['info']    = "未知错误";
        return $res;
    }}

Use jwt to generate token

    /**
     * 使用jwt生成token字符串
     */
    public function setJwtToken()
    {
        $uid = input('uid'); // 接收生成token字符串 如:123
        $token = signToken($uid);
        // 生成字符串: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhYmNkZWZnIiwiYXVkIjoiIiwiaWF0IjoxNjQxNDUwMTU0LCJuYmYiOjE2NDE0NTAxNTcsImV4cCI6MTY0MTQ1NzM1NCwiZGF0YSI6eyJ1aWQiOiIxMjMifX0.I_GAkMsOhtEpIPkizCuQA-b9H6ovSovWx0AwAYI-b0s
        echo $token;die;
    }

    /**
     * 使用jwt验证token字符串
     */
    public function checkJwtToken()
    {
        $token  = input('token'); // 接收生成token字符串
        $result = checkToken($token);
        // Array ( [status] => 200 [data] => Array ( [uid] => 123 ) )
        print_r($result);die;
    }

Create user controller

<?phpdeclare  (strict_types = 1);namespace app\api\controller;use think\facade\Db;use think\Request;class User{
    public function login(Request $request)
    {
        if ($request->isPost()){
            $username = $request->param('username','','trim');
            $password = $request->param('password','','trim');

            //查询数据库
            $user = Db::name('user')->where('username',$username)->find();

            if (!$user){
                return json(['status' => 'fail','msg' => '用户名不存在']);
            }
            if ($user['password']!==md5($password)){
                return json(['status' => 'fail','msg' => '密码错误']);
            }
            $getToken = $this->token($user);
            return json(['status' => 'success','msg' => '登陆成功','token' => $getToken]);
        }
    }
    public function token($user)
    {
        $uid = $user['username']; // 接收生成token字符串 如:123
        $token = signToken($uid);
        dd($token);
    }
    /**
     * 验证token
     */
    public function chToken()
    {
        $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhYmNkZWZnIiwiYXVkIjoiIiwiaWF0IjoxNjQ4MDkwMDkyLCJuYmYiOjE2NDgwOTAwOTIsImV4cCI6MTY0ODA5MDEyMiwiZGF0YSI6eyJ1aWQiOiJcdTVmMjBcdTRlMDlcdTk4Y2UifX0.oJFpNcZ6stMymOCbD-meX0IPEIYLYNcwKxhMItF2cMw';
        $result = checkToken($token);
        // Array ( [status] => 200 [data] => Array ( [uid] => 123 ) )
        print_r($result);die;
    }}

The user logs in successfully and returns to the front end token, the front end stores the token, and carries the token in the header during the next request. The back end accepts the token and verifies it in the middleware

Create api middleware

<?phpdeclare  (strict_types = 1);namespace app\middleware;class Api{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //toke 合法性验证
        $header = $request->header();
        //判读请求头里有没有token
        if(!isset($header['token'])){
            return json(['code'=>440,'msg'=>'request must with token']);
        }
        $token = $header['token'];

        try {
            // token 合法
            $token = checkToken($token);
        }catch (\Exception $e){
            return json(['code'=>440,'msg'=>'invalid token']);
        }

        return $next($request);
    }}

Finally, there are two solutions to how to deal with the issue of token expiration. The first is to set the token time longer so that the token will not expire. However, this has a drawback. Once the client Obtaining this token is equivalent to having a key, and the initiative is in the hands of the user. So this solution is not recommended. The second is back-end processing. When the token expires, the token is reacquired and the new token is passed to the front end. The front end stores the new token, replaces the original token, and carries the new token with the next request. token request.

I am programmer Fengfeng, a programmer who loves learning and tossing.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Detailed example of thinkphp6 using jwt authentication. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete
Previous article:what is model in thinkphpNext article:what is model in thinkphp