Reading time: 4 minutes
In this tutorial, I will show you how to implement JSON Web Tokens (JWT) in PHP. JWT is a secure and easy way to authenticate and authorize users in web applications.
Step 1: Install dependencies
To get started, we need to install the necessary dependencies to work with JWT in PHP. We will use the “firebase/php-jwt” library, which provides support for JWT in PHP.
You can install this library using Composer. If you don’t have Composer installed, you can download it from its official website. Once you have Composer installed, create a new project and add the JWT library by running the following commands in your terminal:
composer init composer require firebase/php-jwt
These commands create a new Composer project and add the JWT library as a dependency.
Step 2: Generate a JWT token
Once we have installed the dependencies, we can start working with JWT. The first thing we need to do is generate a JWT token.
To do this, we first need to define a set of claims that will be included in the token. Claims are key-value pairs used to transmit information about the user and session. Some common claims are “sub” (subject), “iat” (issued at), “exp” (expiration time), and “iss” (issuer).
Next, we will create a function called “generateToken” that will generate a JWT token with the specified claims:
require_once __DIR__ . '/vendor/autoload.php'; use Firebase\JWT\JWT; function generateToken($user_id) { $key = 'secret_key'; $payload = array( 'iss' => 'localhost', 'sub' => $user_id, 'iat' => time(), 'exp' => time() + (60 * 60 * 24) ); $token = JWT::encode($payload, $key); return $token; }
In this example, we are defining a secret key called “secret_key” that will be used to sign the token. We are also including the “iss”, “sub”, “iat”, and “exp” claims. The “sub” claim is set to the user ID, and the “iat” and “exp” claims are set to the current time and one day in the future, respectively.
Finally, we use the JWT library to encode the set of claims into a signed JWT token.
Step 3: Verify a JWT token
Now that we have generated a JWT token, we need to verify it before allowing a user to access protected resources. To do this, we will create a function called “verifyToken” that will verify the token’s signature and return the user data if the token is valid:
function verifyToken($token) { $key = 'secret_key'; try { $decoded = JWT::decode($token, $key, array('HS256')); $user_id = $decoded->sub; return array('success' => true, 'user_id' => $user_id); } catch (Exception $e) { return array('success' => false, 'error' => $e->getMessage()); } }
In this example, we are using the JWT library to decode the token and verify its signature using the secret key “secret_key”.
If the token is valid, we extract the user ID from the “sub” claim and return it along with a success indicator. If the token is invalid, we catch the exception thrown by the JWT library and return an error message.
Step 4: Integrate JWT into a web application
Now that we have generated and verified a JWT token, we can integrate it into a web application. To do this, we will create a login form that prompts the user for their email and password.
When the user submits the form, we will validate their credentials and generate a JWT token if they are valid. We will then store the token in a cookie and redirect the user to a protected page.
In the protected page, we will verify the JWT token stored in the cookie and allow the user to access protected resources if the token is valid.
Here is an example of how to integrate JWT into a web application using PHP:
require_once __DIR__ . '/vendor/autoload.php'; use Firebase\JWT\JWT; // Function to generate a JWT token function generateToken($user_id) { $key = 'secret_key'; $payload = array( 'iss' => 'localhost', 'sub' => $user_id, 'iat' => time(), 'exp' => time() + (60 * 60 * 24) ); $token = JWT::encode($payload, $key); return $token; } // Function to verify a JWT token function verifyToken($token) { $key = 'secret_key'; try { $decoded = JWT::decode($token, $key, array('HS256')); $user_id = $decoded->sub; return array('success' => true, 'user_id' => $user_id); } catch (Exception $e) { return array('success' => false, 'error' => $e->getMessage()); } } // If the login form is submitted if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['email']) && isset($_POST['password'])) { $email = $_POST['email']; $password = $_POST['password']; // Verify user credentials if ($email === 'user@example.com' && $password === 'password') { scss Copy code // Generate a JWT token for the user $token = generateToken(123); // Store the token in a cookie setcookie('token', $token, time() + (60 * 60 * 24), '/'); // Redirect the user to the protected page header('Location: protected.php'); exit(); } else { echo 'Invalid credentials.'; } } // If the user tries to access the protected page if ($_SERVER['REQUEST_URI'] === '/protected.php') { // Verify the JWT token stored in the cookie if (isset($_COOKIE['token'])) { $token = $_COOKIE['token']; $result = verifyToken($token); php Copy code // Allow the user to access protected resources if the token is valid if ($result['success'] === true) { echo 'Welcome, user #' . $result['user_id'] . '!'; } else { // Redirect the user to the login page if the token is invalid header('Location: login.php'); exit(); } } else { // Redirect the user to the login page if there is no token header('Location: login.php'); exit(); } }
In this example, we have created two functions called generateToken
and verifyToken
that are responsible for generating and verifying JWT tokens, respectively. We have also created a login form that prompts the user for their email and password.
When the user submits the form, we validate their credentials and generate a JWT token if they are valid. We then store the token in a cookie and redirect the user to a protected page called “protected.php”.
In the protected page, we verify the JWT token stored in the cookie and allow the user to access protected resources if the token is valid. If the token is invalid or not present, we redirect the user back to the login page.
Conclusion
In summary, JWT is a secure and efficient way to authenticate and authorize users in web and mobile applications. In this tutorial, we have learned how to generate and verify JWT tokens using PHP and the Firebase JWT library.
Remember that when implementing JWT in your application, it is important to keep your secret key secure and use strong encryption algorithms to protect your JWT tokens. You should also consider security best practices such as using HTTPS and validating user input to prevent code injection attacks.
I hope this tutorial has been helpful to you and assists you in implementing JWT in your future web and mobile applications.