Current Location: Home> Latest Articles> Implement JWT Authentication in ThinkPHP6: Complete Guide and Code Example

Implement JWT Authentication in ThinkPHP6: Complete Guide and Code Example

gitbox 2025-06-18

1. What is JWT?

JSON Web Token (JWT) is an open standard (RFC 7519) used for securely transmitting information across networks. A JWT consists of three parts: Header, Payload, and Signature. The header contains information about the type of token and the signing algorithm used, the payload holds the data to be transmitted, and the signature is used to verify the token's authenticity.

2. Using JWT in ThinkPHP6

In ThinkPHP6, JWT can be used by including the think-jwt package in the composer.json file. Add "think-jwt": "1.0.*" to the "require" section of the composer.json file, and then run the composer update command to install the package.

2.1 Generating JWT

In ThinkPHP6, JWT can be generated using the JWT class. First, create a jwt.php configuration file that contains the necessary JWT settings.

        return [
            // Signing key
            'secret' => 'my_secret',
            // Expiration time in seconds, default is 1 hour
            'expire' => 3600,
        ];
    

Then, in your controller, import the JWT class and use the create method to generate a JWT.

        use think\jwt\JWT;

        class UserController extends Controller {
            public function login() {
                // Validate username and password
                ...
                
                // Generate JWT
                $payload = [
                    'user_id' => $user->id
                ];
                $jwt = JWT::create($payload);
                
                return ['token' => $jwt];
            }
        }
    

In the code above, the username and password are validated first, and after successful validation, the JWT is generated and returned to the client.

2.2 Validating JWT

In ThinkPHP6, the validity of a JWT can be checked using the verify method of the JWT class.

        use think\jwt\JWT;

        class UserController extends Controller {
            public function profile() {
                // Validate JWT
                $jwt = input('token');
                $payload = JWT::verify($jwt);
                
                return ['user_id' => $payload['user_id']];
            }
        }
    

In the code above, the JWT is first retrieved from the client, and then the verify method is called to check its validity. Once verified, the payload data from the JWT can be accessed.

3. Conclusion

Through this article, we have learned the basic concepts of JWT and how to use it in ThinkPHP6. Using JWT for authentication is an effective way to secure your APIs and prevent unauthorized access. In practical development, developers can adjust the JWT configuration as needed to meet the security requirements of their projects.