JWT (JSON Web Token) is an open standard (RFC 7519) used for securely transmitting tokens in web applications. It is widely used for user authentication and authorization. ThinkPHP6, a popular PHP framework, offers rich component support that facilitates integrating JWT authentication. This article will walk you through implementing JWT authentication in ThinkPHP6 step-by-step.
First, install the JWT extension library using Composer. Navigate to your project root directory and run the following command in the terminal:
<span class="fun">composer require firebase/php-jwt</span>
After installation, create or edit the jwt.php configuration file in ThinkPHP6's config directory with the following content:
return [
'secret' => 'your_secret_key',
'algorithm' => 'HS256',
];
Here, secret is the signing key, recommended to be a random string. algorithm specifies the encryption algorithm and can be HS256, HS384, or HS512.
Authentication middleware validates JWT tokens before requests reach the controller. Generate the middleware quickly with the command:
<span class="fun">php think make:middleware JwtMiddleware</span>
This will create a JwtMiddleware class in the app/middleware directory.
Open the JwtMiddleware file and add the authentication logic as follows:
use think\facade\Request;
use think\facade\Response;
use Firebase\JWT\JWT;
class JwtMiddleware
{
public function handle($request, \Closure $next)
{
$token = Request::header('Authorization');
if (empty($token)) {
return Response::create('Unauthorized', '401');
}
try {
JWT::decode($token, config('jwt.secret'), [config('jwt.algorithm')]);
} catch (\Exception $e) {
return Response::create('Invalid token', '401');
}
return $next($request);
}
}
The code retrieves the JWT token from the request header; if empty, returns a 401 error. It then attempts to validate the token and returns 401 if validation fails. If successful, the request proceeds.
In the route/route.php file, add middleware to routes requiring authentication:
\think\Route::group(function () {
// Authenticated routes
})->middleware(\app\middleware\JwtMiddleware::class);
You can also declare middleware usage in controller annotations:
namespace app\controller;
use think\annotation\route\Post;
use app\middleware\JwtMiddleware;
/**
* @route("auth")
* @middleware(JwtMiddleware::class)
*/
class AuthController
{
// Controller code
}
This applies the JWT middleware to all routes within the controller.
After setup, use Postman or similar API testing tools to send requests with valid JWT tokens to verify access. Invalid or missing tokens should receive a 401 Unauthorized response.
This article demonstrated how to integrate JWT authentication into ThinkPHP6. It included extension installation, configuration, middleware creation and application, plus interface testing. Implementing JWT enhances application security and user identity management efficiency.