Token Validation (PHP)
Token validation can be performed in several ways: through the JWTEAuth service’s checkToken method, or by manually validating the token on the backend server from the client side. This process is crucial for ensuring that the user is granted the appropriate authorization.
Token validation via JWTEAuth service checkToken Example :
header('Content-Type: application/json');
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (isset($data['jwtToken']) && !empty($data['jwtToken'])) {
$jwtToken = $data['jwtToken'];
$apiKey = 'xxxx-yyyy-zzzz'; // static api key from jwteauth vendor
$origin = 'https://yourdomain.com'; // domain name
$headers = [
"Origin: $origin",
"Authorization: Bearer $apiKey",
"X-JWT-Token: $jwtToken"
];
$url = 'https://server1.jwteauth/endpoint/checkToken'; // static url endpoint
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$data = json_decode($response, true);
if (curl_errno($ch)) {
echo json_encode([
'status' => 'error',
'message' => curl_error($ch)
]);
} else {
/* roles assignment */
//-- user authorization
//-- redirect page
}
curl_close($ch);
} else {
//-- Token not found.
}
{
status: "valid", // valid/invalid
msg: 'Token is valid',
user: {
userId: '1234',
userName: 'Dudu Dada'
}
}
JWT PHP Native Example : https://github.com/firebase/php-jwt
<?php
require "vendor/autoload.php";
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\SignatureInvalidException;
use Firebase\JWT\BeforeValidException;
header('Content-Type: application/json');
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (isset($data['jwtToken']) && !empty($data['jwtToken'])) {
$jwtToken = $data['jwtToken'];
$secretKey = 'secretkey123456'; // get secret key at client zone > domain
try {
$decoded = JWT::decode($jwtToken, new Key($secretKey, 'HS256'));
echo json_encode([
'status' => 'success',
'message' => "Valid Token"
]);
} catch (ExpiredException $e) {
echo json_encode([
'status' => 'error',
'message' => "Token is expired: " . $e->getMessage()
]);
} catch (SignatureInvalidException $e) {
echo json_encode([
'status' => 'error',
'message' => "Signature is not valid: " . $e->getMessage()
]);
} catch (BeforeValidException $e) {
echo json_encode([
'status' => 'error',
'message' => "Token is invalid: " . $e->getMessage()
]);
} catch (Exception $e) {
echo json_encode([
'status' => 'error',
'message' => "Other error: " . $e->getMessage()
]);
}
} else {
echo json_encode([
'status' => 'error',
'message' => 'Token not found.'
]);
}?>
📅January 13, 2025