DEV Community

Cover image for How does JWT work?
Automata
Automata

Posted on

How does JWT work?

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
Enter fullscreen mode Exit fullscreen mode

Header: Contains information about of algorithm and token type.

{
  "alg": "HS256",
  "typ": "JWT"
}
Enter fullscreen mode Exit fullscreen mode

Payload:Contains the data that you would like send.

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}
Enter fullscreen mode Exit fullscreen mode

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
)
Enter fullscreen mode Exit fullscreen mode

Libraries: firebase/php-jwt

composer require firebase/php-jwt
Enter fullscreen mode Exit fullscreen mode
<?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();
}
?>

Enter fullscreen mode Exit fullscreen mode

Aux Tools:

https://jwt.io/

Top comments (0)