Simply put, JWT is a Token in json format working in the web.
JWT is composed of three parts: Header, payload, signature.
The structure of this looks like this xxxxx.yyyyy.zzzzz
.
# Example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Header: Contains information about of algorithm and token type.
{
"alg": "HS256",
"typ": "JWT"
}
Payload:Contains the data that you would like send.
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
Signature: For last, the signature do create encoding the Header, Payload and the SECRET. The SECRET must be shared between emisor and receptor.
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
Libraries: firebase/php-jwt
composer require firebase/php-jwt
<?php
require_once 'vendor/autoload.php';
use \Firebase\JWT\JWT;
// Generate a JWT
$secret= "my_secret";
$payload = array(
"sub" => "1234567890",
"name" => "John Doe",
"admin" => true,
"iat" => time(),
"exp" => time() + (60 * 60) // JWT valid for 1 hour
);
$jwt = JWT::encode($payload, $secret);
echo "JWT generated: " . $jwt . "\n\n";
// Verify a JWT
try {
$decoded = JWT::decode($jwt, $clave_secreta, array('HS256'));
echo "JWT verified:\n";
print_r($decoded);
} catch (Exception $e) {
echo "Error verifying el JWT: " . $e->getMessage();
}
?>
Top comments (0)