Current Location: Home> Latest Articles> Complete Guide to Implementing JWT Authentication in ThinkPHP6

Complete Guide to Implementing JWT Authentication in ThinkPHP6

gitbox 2025-07-14

What is JWT?

JWT (JSON Web Token) is an encrypted token used to securely transmit information between web applications. It is transmitted as a JSON object between the client and the server.

How JWT Works

JWT consists of three parts: Header, Payload, and Signature.

Header: Declares the token type and the encryption algorithm used. Example:

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload: Contains standard claims and custom claims. Example:

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

Signature: Generated by signing the Base64-encoded Header and Payload together with a secret key.

Steps to Use JWT Authentication in ThinkPHP6

Install the JWT Extension

To use JWT authentication in ThinkPHP6, you first need to install the JWT extension. Add the following dependency in the composer.json file in your project directory:

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

Then, run the composer install command to install the JWT extension.

Generate Token

After successful login, you can generate a token and return it to the client. Example code:

use think\jwt\JWT;

public function login() {
  // Login logic
  $payload = [
    'sub' => $user->id,
    'name' => $user->username,
    'iat' => time()
  ];
  $token = JWT::encode($payload, $key);
  return json(['token' => $token]);
}

Verify Token

To verify the user's identity, you can use JWT to validate the token's validity. Example code:

use think\jwt\JWT;

public function getUser(Request $request) {
  $token = $request->header('Authorization');
  try {
    $payload = JWT::decode($token, $key, ['HS256']);
    $user = User::get($payload->sub);  // Retrieve user information from the database
    return json($user);
  } catch (Exception $e) {
    return json(['error' => 'Token is invalid']);
  }
}

Conclusion

JWT is a convenient and secure authentication method, and implementing JWT authentication in ThinkPHP6 is straightforward. By generating and verifying tokens, you can effectively secure user identities. Additionally, it's important to keep your secret key safe and set appropriate token expiration times to further enhance system security.