在ThinkPHP中使用JWT进行身份验证,可以按照以下步骤进行:
composer require firebase/php-jwt
<?php
return [
// JWT密钥
'secret' => 'your_secret_key_here',
// JWT过期时间,单位为秒
'expire' => 3600,
];
<?php
namespace app\service;
use Firebase\JWT\JWT;
use think\facade\Config;
class JwtService
{
// 生成JWT
public static function generate(array $data)
{
$config = Config::get('jwt');
$time = time();
$payload = [
'iss' => 'your_domain_here',
'iat' => $time,
'exp' => $time + $config['expire'],
'data' => $data,
];
return JWT::encode($payload, $config['secret']);
}
// 验证JWT
public static function verify($token)
{
try {
$config = Config::get('jwt');
$decoded = JWT::decode($token, $config['secret'], array('HS256'));
return (array) $decoded->data;
} catch (\Exception $e) {
return false;
}
}
}
<?php
namespace app\controller;
use app\service\JwtService;
use think\exception\HttpException;
use think\Request;
class UserController
{
// 需要验证身份的方法
public function profile(Request $request)
{
$authorization = $request->header('Authorization');
if (!$authorization) {
throw new HttpException(401, 'Authorization Required');
}
$token = str_replace('Bearer ', '', $authorization);
$user = JwtService::verify($token);
if (!$user) {
throw new HttpException(401, 'Invalid Token');
}
return json($user);
}
}
以上就是在ThinkPHP中使用JWT进行身份验证的基本步骤和代码示例。关键词包括:JWT、composer、firebase/php-jwt、Config、生成JWT、验证JWT、控制器方法、请求头、Authorization。