JWT Tokens in PHP: Complete Guide to the firebase/php-jwt Library
JSON Web Token (JWT) is a compact and secure way to transmit data between a client and server in JSON format. In modern web development, JWT is widely used for user authentication and authorization, as well as for exchanging information between various services. In PHP, the most popular and reliable library for working with JWT is firebase/php-jwt.
What is JWT and Why is it Needed?
JWT consists of three parts separated by dots:
- Header — contains information about the token type and signing algorithm.
- Payload — contains the data (e.g., user ID, role, expiration time).
- Signature — created using a secret key or an RSA/ECDSA key pair.
Main advantages of JWT:
- No need to store sessions on the server (stateless).
- Can contain any data in JSON format.
- Supports various signing algorithms: HS256, RS256, ES256, and others.
- Resistant to forgery due to cryptographic signature.
Installing the firebase/php-jwt Library
To install the library, use Composer. Open a terminal in the root folder of your project and run the command:
composer require firebase/php-jwtAfter installation, include the Composer autoloader in your PHP script:
<?phprequire_once __DIR__ . '/vendor/autoload.php';
use Firebase\\JWT\\JWT;use Firebase\\JWT\\Key;?>Creating a JWT Token
To create a token, you need to define the payload and sign it with a secret key. Example of creating a token with the HS256 algorithm:
<?php$key = 'your-secret-key-here'; // Secret key (at least 32 characters)$payload = [ 'iss' => 'pythonlib.ru', // Token issuer 'sub' => '1234567890', // Subject (e.g., user ID) 'name' => 'Ivan Ivanov', 'role' => 'user', 'iat' => time(), // Issued at time 'exp' => time() + 3600 // Expiration time (1 hour)];
$jwt = JWT::encode($payload, $key, 'HS256');echo "Created JWT token:" . $jwt;?>In this example, we set standard fields: iss (issuer), sub (subject), iat (issued at), and exp (expiration). You can add any custom fields, such as role or email.
Decoding and Verifying a JWT Token
When receiving a token from the client, you need to verify its signature and expiration. The library automatically checks the algorithm and signature validity:
<?phptry { $decoded = JWT::decode($jwt, new Key($key, 'HS256')); print_r($decoded);} catch (\\Firebase\\JWT\\ExpiredException $e) { echo "Error: token expired — " . $e->getMessage();} catch (\\Firebase\\JWT\\SignatureInvalidException $e) { echo "Error: invalid signature — " . $e->getMessage();} catch (\\Exception $e) { echo "Error: " . $e->getMessage();}?>The decode() method returns a stdClass object with the payload data. If the token is invalid, an appropriate exception is thrown. It is recommended to always handle ExpiredException and SignatureInvalidException exceptions.
Using Asymmetric Encryption (RS256)
For enhanced security, use the RS256 algorithm with a key pair (private/public). This is especially relevant in microservice architecture:
<?php// Key generation (run once)// openssl genrsa -out private.pem 2048// openssl rsa -in private.pem -pubout -out public.pem
$privateKey = file_get_contents('