JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties over a network. A JWT consists of three parts: the header, the payload, and the signature. The header typically contains the type of the token and the signing algorithm used. The payload contains the data being transmitted, and the signature is used to verify the authenticity of the token.
In ThinkPHP6, you can use JWT by including the think-jwt package in your project. To do this, add the package to your `composer.json` file and install it via Composer.
{ "require": { "think-jwt": "1.0.*" } }
Once installed, you can use the following code for JWT authentication:
In ThinkPHP6, JWT can be generated using the `JWT` class. First, you need to create a `jwt.php` configuration file that contains the related JWT settings. This file should be placed in the `config` directory.
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 call the `create` method to generate the 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 this code, the username and password are validated first. If the validation is successful, a JWT is generated and returned to the client.
In ThinkPHP6, JWT can be verified for its validity using the `JWT` class. In your controller, import the JWT class and call the `verify` method to validate the JWT.
use think\jwt\JWT; class UserController extends Controller { public function profile() { // Verify JWT $jwt = input('token'); $payload = JWT::verify($jwt); return ['user_id' => $payload['user_id']]; } }
In this code, we first get the JWT sent by the client and call the `verify` method to validate it. If valid, we can access the payload data inside the JWT.
Through this article, we have learned about the basic concepts of JWT and how to use it for authentication in ThinkPHP6. JWT authentication effectively protects API security, preventing unauthorized access. Developers can customize the configuration to meet project-specific needs while ensuring both security and flexibility of the authentication system.