Facebook
From Kiros, 8 Months ago, written in PHP.
Embed
Download Paste or View Raw
Hits: 417
  1. class JwtService
  2. {
  3.     private $secretKey;
  4.  
  5.     public function __construct()
  6.     {
  7.         $this->secretKey = $_ENV['APP_SECRET'];
  8.     }
  9.  
  10.     public function generateToken(UserInterface $user, int $expiration = 3600): string
  11.     {
  12.         $payload = [
  13.             'sub' => $user->getUserIdentifier(),
  14.             'exp' => time() + $expiration,
  15.         ];
  16.  
  17.         return JWT::encode($payload, $this->secretKey, 'HS256');
  18.     }
  19.  
  20.     public function validateToken(string $token): bool
  21.     {
  22.         try {
  23.             JWT::decode($token, new Key($this->secretKey, 'HS256'));
  24.             return true;
  25.         } catch (Exception $e) {
  26.             return false;
  27.         }
  28.     }
  29. }