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.
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.
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.
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]);
}
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']);
}
}
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.