Using JWT for Secure Authentication in PHP

This article explains how to install the PHP‑JWT library with Composer, generate JSON Web Tokens using JWT::encode, validate them with JWT::decode, and configure custom expiration and not‑before times to enhance authentication security in PHP applications.

php Courses
php Courses
php Courses
Using JWT for Secure Authentication in PHP

In modern web application development, protecting user authentication information is crucial. JSON Web Token (JWT) provides a secure method by encoding authentication data in JSON format and signing it to ensure integrity.

Install JWT

First, install the JWT library in a PHP project using the Composer tool. Run the following command:

composer require firebase/php-jwt

Generate JWT

After a user successfully authenticates, generate a JWT and return it to the client. The following PHP code demonstrates how to create a token:

use Firebase\JWT\JWT;

$payload = array(
    "user_id" => 1234,
    "email" => "[email protected]"
);

$secret_key = "secret_key";
$jwt = JWT::encode($payload, $secret_key);

Use the JWT::encode() method where the first argument is an associative array containing user information and the second argument is the secret key used for signing.

Validate JWT

Clients store the JWT locally and send it with each request. To verify the token in PHP, use the following code:

use Firebase\JWT\JWT;

$jwt = "generated_jwt";
$secret_key = "secret_key";
try {
    $decoded = JWT::decode($jwt, $secret_key, array("HS256"));
    $user_id = $decoded->user_id;
    $email = $decoded->email;
} catch (Exception $e) {
    // JWT verification failed
}

The JWT::decode() method takes the token, the secret key, and the allowed signing algorithms. If verification succeeds, it returns an object containing the user data.

Custom Expiration and Not‑Before Time

By default, JWTs have no expiration, but you can enhance security by setting an "exp" (expiration) and "nbf" (not before) claim:

use Firebase\JWT\JWT;

$payload = array(
    "user_id" => 1234,
    "email" => "[email protected]",
    "exp" => time() + 3600, // valid for 1 hour
    "nbf" => time() + 30    // not valid for the first 30 seconds
);

$secret_key = "secret_key";
$jwt = JWT::encode($payload, $secret_key);

When validating with JWT::decode(), an expired or not‑yet‑valid token will cause an exception, allowing you to reject the request.

Using JWT in PHP provides a secure authentication mechanism; by leveraging the PHP‑JWT library to generate, verify, and manage token lifetimes, developers can protect user credentials while handling errors and secret keys carefully.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AuthenticationWeb DevelopmentPHPJWT
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.