search
HomePHP FrameworkThinkPHPHow to use ThinkPHP6 for JWT authentication?

How to use ThinkPHP6 for JWT authentication?

Jun 12, 2023 pm 12:18 PM
thinkphpCertificationjwt

JWT (JSON Web Token) is a lightweight authentication and authorization mechanism that uses JSON objects as security tokens to securely transmit user identity information between multiple systems. ThinkPHP6 is an efficient and flexible MVC framework based on PHP language. It provides many useful tools and functions, including JWT authentication mechanism. In this article, we will introduce how to use ThinkPHP6 for JWT authentication to ensure the security and reliability of web applications.

  1. Installing and Configuring the JWT Extension

First, we need to install the JWT extension in our application. It can be installed by adding dependencies in the composer.json file:

{
    "require": {
        "firebase/php-jwt": "^5.0.0"
    }
}

Then run the following command to install it:

composer install

After the installation is complete, we need to configure JWT in the configuration file. Create the jwt.php file in the config directory and add the following content:

<?php
return [
    'key' => 'your-secret-key',
    'alg' => 'HS256',
    'exp' => 7200, // token过期时间,单位秒
];

where "key" is a string used to generate the signature key of the JWT token, and "alg" is the JWT signature algorithm Name, we can choose algorithms such as "HS256", "HS512", "RS256", etc. "exp" is the expiration time of the JWT token, calculated in seconds.

  1. Implementing JWT authentication controller

Next, we need to create a JWT authentication controller to implement JWT authentication. Create the AuthController.php file in the app/controller directory and add the following content:

<?php
namespace appcontroller;

use FirebaseJWTJWT;
use thinkacadeDb;

class AuthController
{
    public function login()
    {
        //在这里处理用户登陆逻辑
        //...
        
        //登陆成功后生成JWT token并返回给客户端

        $secretKey = config('jwt.key'); // 获取JWT生成签名的密钥
        $alg = config('jwt.alg'); // 获取JWT加密算法
        $payload = [
            'sub' => $user->id, // 存储用户ID
            'exp' => time() + config('jwt.exp'), // 设定过期时间
        ];
        $jwt = JWT::encode($payload, $secretKey, $alg); // 生成JWT令牌
        return ['token' => $jwt]; // 返回JWT Token给客户端
    }

    public function dashboard()
    {
        //检查请求中的JWTToken是否有效,并返回用户信息

        $jwtToken = request()->header('Authorization'); // 获取JWT Token
        if (!$jwtToken) {
            // 如果token不存在,直接返回错误信息
            return ['msg' => '未验证身份,请先登录'];
        }
        $jwtInfo = JWT::decode($jwtToken, config('jwt.key'), [config('jwt.alg')]); // 使用JWT解密Token
        $userId = $jwtInfo->sub; // 获取token中存储的用户ID,用来查询用户信息
        $user = Db::table('users')->where('id', $userId)->find(); // 查询用户信息
        if (!$user) {
            // 用户不存在,直接返回错误信息
            return ['msg' => '用户不存在'];
        }
        // 返回用户信息
        return ['username' => $user['username'], 'email' => $user['email']];
    }
}

In the above controller code, we have implemented two functions: one is user login, the other is to obtain user information . During the login process, we generate a JWT token and return it to the client for authentication in subsequent requests. In the dashboard method, we check whether the Authorization header of the request contains the JWT token, and use the JWT to decrypt the token and verify whether the user's identity is valid.

  1. Add JWT authentication middleware

Finally, we need to add a JWT authentication middleware to the application to protect the API interface that requires authentication. Create the JwtAuth.php file in the app/middleware directory and add the following content:

<?php
namespace appmiddleware;

use FirebaseJWTJWT;
use thinkacadeConfig;

class JwtAuth
{
    public function handle($request, Closure $next)
    {
        //检查请求中的JWTToken是否有效

        $jwtToken = $request->header('Authorization'); // 获取JWT Token
        if (!$jwtToken) {
            // 如果token不存在,直接返回错误信息
            return response(['msg' => '未授权的API请求!'], 401);
        }
        try {
            $jwtInfo = JWT::decode($jwtToken, Config::get('jwt.key'), [Config::get('jwt.alg')]); // 使用JWT解密Token
            $request->jwtInfo = $jwtInfo; // 将解密后的JWT信息存储在请求对象中,后续控制器可以使用
            return $next($request); // 继续后续请求处理
        } catch (Exception $e) {
            // JWT Token过期或者解密失败,返回错误信息
            return response(['msg' => 'JWT Token无效或已过期!'], 401);
        }
    }
}

In the above code, we checked whether the Authorization header of the request contains a valid JWT token. If the JWT token is invalid or has expired, we return an Unauthorized HTTP response, otherwise we continue subsequent request processing and store the JWT token's information in the request object for use by subsequent controllers.

Finally, we need to use JWT authentication middleware in the application's routing to protect the API interface that requires authentication. For example, we add the following code in the routes/api.php file:

<?php
use appmiddlewareJwtAuth;

// 需要JWT认证的API接口
Route::get('dashboard', 'AuthController@dashboard')->middleware(JwtAuth::class);

In the above code, we have protected the dashboard method using the JwtAuth middleware to ensure that there are only requests with valid JWT tokens to access it.

Conclusion

In this article, we introduced how to use ThinkPHP6 for JWT authentication to ensure the security and reliability of web applications. We first installed and configured the JWT extension, then implemented the JWT authentication controller and JWT authentication middleware, and finally used the JWT authentication middleware in the routing of the application to protect the API interfaces that require authentication. Through these steps, we can easily implement the JWT authentication mechanism in ThinkPHP6 applications to ensure the security and reliability of web applications.

The above is the detailed content of How to use ThinkPHP6 for JWT authentication?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor