JwtService.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace App\Services;
  3. use App\Models\User;
  4. use Firebase\JWT\JWT;
  5. use Exception;
  6. use Firebase\JWT\Key;
  7. use Illuminate\Support\Facades\Cache;
  8. class JwtService
  9. {
  10. // 你的密钥,建议保存在环境变量中
  11. private $secretKey;
  12. private $exp;
  13. public function __construct()
  14. {
  15. $this->secretKey = config('app.jwt_secret');
  16. $this->exp = config('app.jwt_exp');
  17. }
  18. // 生成 JWT
  19. public function generateToken($user)
  20. {
  21. $issuedAt = time();
  22. $expirationTime = $issuedAt + $this->exp;
  23. $payload = [
  24. 'iat' => $issuedAt,
  25. 'exp' => $expirationTime,
  26. 'sub' => $user->id,
  27. 'user_id' => $user->id,
  28. ];
  29. $token = JWT::encode($payload, $this->secretKey, 'HS256');
  30. if ($user instanceof User) {
  31. Cache::put("user_{$user->id}_jwt", $token, $this->exp);
  32. }
  33. return $token;
  34. }
  35. // 验证 JWT
  36. public function validateToken($token)
  37. {
  38. try {
  39. $decoded = JWT::decode($token, new Key($this->secretKey, 'HS256'));
  40. return (object)$decoded; // 返回解码后的 JWT 数据
  41. } catch (Exception $e) {
  42. return null; // Token 无效或过期
  43. }
  44. }
  45. }