Encode and Decode JSON Web Tokens in PHP
JSON Web Token (JWT) is a widely used standard for securely transmitting information between parties as a JSON object. It has become a popular authentication and authorization mechanism in modern web development. JWT is designed to be compact, self-contained, and easily verifiable, making it an efficient and secure way to handle data exchange.
How JWT works?
JWT consists of three parts separated by dots: header, payload, and signature. The header typically contains the token type (JWT) and the signing algorithm used. The payload carries the claims or data you want to transmit, such as user information or authorization details. The signature is generated using a secret key, ensuring the integrity of the token and preventing tampering.
The typical flow involves a server generating a JWT after successful authentication and sending it to the client. The client includes the JWT in subsequent requests to access protected resources. The server then decodes and verifies the JWT to grant access to the requested resources or services.
JWT Syntax
1 | header.payload.signature |
Install Required Library
First, you need to install the firebase/php-jwt library, which provides functionality for encoding and decoding JWTs in PHP. You can install it using Composer with the following command:
1 | composer require firebase/php-jwt |
Example: Encoding a JWT in PHP
Let’s demonstrate how to create a JWT in PHP using the firebase/php-jwt
library.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?php require "vendor/autoload.php"; use Firebase\JWT\JWT; // Set the secret key $secret_key = "YOUR_SECRET_KEY"; // Create the token payload with necessary claims $payload = [ "user_id" => 1234, "username" => "john_doe", "role" => "admin", // Add more claims as needed ]; // Generate the JWT token $jwt = JWT::encode($payload, $secret_key); // Output the generated JWT echo $jwt; ?> |
Output:
1 | eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMjM0LCJ1c2VybmFtZSI6ImpvaG5fZG9lIiwicm9sZSI6ImFkbWluIiwiZXhwIjoxNjMyMjM5MTI2fQ.6NINvjSxJtQ6z0uU4T5X_Bva2v-2TJqduy1dHLc6OFc |
Example: Decoding a JWT in PHP
Now, let’s decode and verify the JWT token on the server side.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?php require "vendor/autoload.php"; use Firebase\JWT\JWT; // Set the secret key $secret_key = "YOUR_SECRET_KEY"; // Example JWT token (replace this with the actual JWT you want to decode) $jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMjM0LCJ1c2VybmFtZSI6ImpvaG5fZG9lIiwicm9sZSI6ImFkbWluIiwiZXhwIjoxNjMyMjM5MTI2fQ.6NINvjSxJtQ6z0uU4T5X_Bva2v-2TJqduy1dHLc6OFc"; try { // Decode the JWT and verify the signature $decoded = JWT::decode($jwt, $secret_key, ["HS256"]); // Output the decoded claims print_r($decoded); } catch (Exception $e) { // Handle JWT validation errors echo "Access denied: " . $e->getMessage(); } ?> |
Output:
1 2 3 4 5 6 | Array ( [user_id] => 1234 [username] => john_doe [role] => admin ) |
Decode a JSON Web Token without using Composer
Step 1: Download the library files
First, download the firebase/php-jwt
library directly from GitHub and place it in your project directory. You can find the library here: https://github.com/firebase/php-jwt
Create a new folder in your project, for example, php-jwt
, and place the src
folder from the library inside it.
Your project structure should look like this:
- your_project
- php-jwt
- src
- JWT.php
- BeforeValidException.php
- ExpiredException.php
- SignatureInvalidException.php
- src
- decode_jwt.php
- php-jwt
Step 2: Create the decode_jwt.php
file
Now, create a new PHP file (e.g., decode_jwt.php
) in the same directory as your library folder. In this file, you can use the following code to decode the JWT:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php require "php-jwt/src/JWT.php"; require "php-jwt/src/BeforeValidException.php"; require "php-jwt/src/ExpiredException.php"; require "php-jwt/src/SignatureInvalidException.php"; use Firebase\JWT\JWT; $jwt = "YOUR_JWT_HERE"; // Replace "YOUR_JWT_HERE" with the actual JWT you want to decode $secret_key = "YOUR_SECRET_KEY_HERE"; // Replace "YOUR_SECRET_KEY_HERE" with your JWT secret key try { $decoded = JWT::decode($jwt, $secret_key, ["HS256"]); print_r($decoded); } catch (Exception $e) { echo "Error: " . $e->getMessage(); } ?> |
Now, when you run the decode_jwt.php
file, it will decode the JWT using the manually included firebase/php-jwt
library. Make sure you have the correct JWT and secret key for decoding, and that you have placed the library files in the proper location as shown in the project structure above.
Note: If your PHP version is 7.x or earlier and you encounter compatibility issues with the latest version of firebase/php-jwt, you can resolve this by using an older version (v5.2.0) of the library. Download the firebase/php-jwt v5.2.0 library from the GitHub repository: firebase/php-jwt/releases/tag/v5.2.0. After downloading, include the relevant files in your PHP project. If your PHP version is 8.x or later, you can continue to use the latest version of firebase/php-jwt without any compatibility issues.
By following this note and using the appropriate version of the library, you can avoid any potential errors related to PHP version compatibility.
Conclusion
JSON Web Tokens (JWT) provide a secure and efficient way to handle data exchange, authentication, and authorization in PHP applications. By understanding JWT’s syntax and using the firebase/php-jwt
library, or manually including the relevant files, you can easily create and validate JWT tokens, ensuring secure communication between parties.
Remember to keep your secret key secure and avoid exposing it in your code or version control systems. Properly handling JWT tokens enhances the security of your application and protects sensitive information.
With the knowledge gained from this blog post, you can confidently integrate JWT into your PHP projects, improving authentication and data exchange mechanisms. Happy coding!