Viewing file: generate_token.php (2.32 KB) -rw-r--r-- Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
<?php
// generate_token.php — Helper to produce HS256 JWTs for ?t=... links
// Usage (CLI):
// ONE_TIME_SECRET=your_secret php generate_token.php --sub=user@example.com --aud=https://example.com --days=14
// Web (GET):
// /generate_token.php?sub=user@example.com&aud=https://example.com&days=14
//
// Sets: iss, iat, exp; optional aud, sub.
$config = is_file(__DIR__.'/config.php') ? include __DIR__.'/config.php' : [];
$secret = $config['ONE_TIME_SECRET'] ?? getenv('ONE_TIME_SECRET');
if (!$secret) {
http_response_code(500);
echo 'ONE_TIME_SECRET not found. Run setup_env.php first.';
exit;
}
function b64url_encode(string $data): string {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
$config = is_file(__DIR__.'/config.php') ? include __DIR__.'/config.php' : [];
$secret = $config['ONE_TIME_SECRET'] ?? getenv('ONE_TIME_SECRET');
if (!$secret) {
http_response_code(500);
echo 'ONE_TIME_SECRET not found. Run setup_env.php first.';
exit;
}
$sub = null;
$aud = null;
$days = 14;
if (PHP_SAPI === 'cli') {
// Command line usage
foreach ($argv as $arg) {
if (preg_match('/^--sub=(.+)$/', $arg, $m)) $sub = $m[1];
elseif (preg_match('/^--aud=(.+)$/', $arg, $m)) $aud = $m[1];
elseif (preg_match('/^--days=(\d+)$/', $arg, $m)) $days = (int)$m[1];
}
} else {
// Web usage
$sub = $_GET['sub'] ?? null;
$aud = $_GET['aud'] ?? null;
$days = isset($_GET['days']) ? max(1, (int)$_GET['days']) : 14;
}
$now = time();
$exp = $now + ($days * 86400);
$iss = $_SERVER['HTTP_HOST'] ?? 'self';
$header = ['typ'=>'JWT','alg'=>'HS256'];
$payload = ['iss'=>$iss,'iat'=>$now,'exp'=>$exp];
if ($sub) $payload['sub'] = $sub;
if ($aud) $payload['aud'] = $aud;
$h64 = b64url_encode(json_encode($header));
$p64 = b64url_encode(json_encode($payload));
$sig = hash_hmac('sha256', $h64.'.'.$p64, $secret, true);
$s64 = b64url_encode($sig);
$jwt = $h64.'.'.$p64.'.'.$s64;
// Output URL
$scheme = 'https';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$path = '/login_flow.php';
$link = $scheme.'://'.$host.$path.'?t='.$jwt;
header('Content-Type: text/plain');
echo "JWT: $jwt\nLink: $link\n";
echo "Expires: " . gmdate('Y-m-d H:i:s', $exp) . " UTC\n";
if ($sub) echo "Subject: $sub\n";
if ($aud) echo "Audience: $aud\n";
?>
|