Table of Contents
thinkphp6 Using jwt
Install jwt extension
After installation, go to the firebase folder in the vender directory
Call the encode and decode methods in JWT to generate tokens and verify tokens
First introduce JWT, and then write two methods to generate signature verification and verification tokens.
Use jwt to generate token
Create user controller
Create api middleware
Home PHP Framework ThinkPHP Detailed example of thinkphp6 using jwt authentication

Detailed example of thinkphp6 using jwt authentication

Jun 24, 2022 pm 12:57 PM
thinkphp

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

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

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

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

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

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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

Development suggestions: How to use the ThinkPHP framework for API development Development suggestions: How to use the ThinkPHP framework for API development Nov 22, 2023 pm 05:18 PM

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.

See all articles