PHP to validate a JSON Web Token (JWT)


Validating a JSON Web Token (JWT) in PHP

JWT Structure and Validation

A JWT consists of three parts: header, payload, and signature. To validate a JWT, the following steps are required:

  • Header Validation:

    • Decode the header and verify the algorithm and token type.
    • Ensure that the algorithm is supported.
  • Payload Validation:

    • Decode the payload and verify its contents.
    • Check the issuer (iss), audience (aud), and expiration time (exp) claims.
  • Signature Validation:

    • Compute the signature using the provided algorithm, header, and payload.
    • Compare the computed signature with the signature in the JWT.

Implementation in PHP

<?php
// Include the Firebase JWT library
require_once 'vendor/autoload.php';

use Firebase\JWT\JWT;

// Specify the JWT to be validated
$jwt = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJtaXJuYW1lIiwiaWF0IjoxNjE1NzE0NTg4LCJleHAiOjE2MTU3MjgzODgsImF1ZCI6ImRhdGFzY2llbmNlIiwic3ViIjoiYWRtaW5AZXhhbXBsZS5jb20iLCJyb2xlcyI6WyJ1c2VyIiwidXNlci1hZG1pbiJdfQ.gU8lZ3fJ3B34-iwBd0gmuPJ1KqIxwZyUYv8v01nx0DA';

// Specify the secret key used to sign the JWT
$secretKey = 'my_secret_key';

try {
  // Decode the JWT using the secret key
  $decoded = JWT::decode($jwt, $secretKey, array('HS256'));

  // Check the issuer and audience claims
  if ($decoded->iss !== 'myrnami' || $decoded->aud !== 'datascience') {
    throw new Exception('Invalid issuer or audience');
  }

  // Check the expiration time
  if ($decoded->exp < time()) {
    throw new Exception('Token has expired');
  }

  // Token is valid
  echo 'JWT is valid';
} catch (Exception $e) {
  // Error handling
  echo 'JWT is invalid: ' . $e->getMessage();
}

Explanation

  • The Firebase JWT library is used to decode and verify the JWT.
  • The secret key is specified to validate the signature.
  • The decoded JWT is checked for valid issuer, audience, and expiration time.
  • If the validation is successful, a message indicating the validity of the JWT is printed. Otherwise, an error message is displayed.

Effective Implementation Tips

  • Use a robust JWT library for secure and reliable validation.
  • Store the secret key securely and use it only in a trusted environment.
  • Ensure that the issuer and audience claims match the expected values.
  • Validate the expiration time to prevent the use of expired tokens.
  • Handle JWT validation errors appropriately, such as by invalidating the token or revoking user access.