Created
September 26, 2022 17:18
-
-
Save kerryj89/67ad49bd63d911b9178e289e478ed4a0 to your computer and use it in GitHub Desktop.
Generate JWT for GitHub App in PHP (no dependencies)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// GitHub App requires JWT. This PHP script below generates that for us. | |
function base64url_encode($input) { | |
return rtrim(strtr(base64_encode($input), '+/', '-_'), '='); | |
} | |
$header = [ | |
'typ' => 'JWT', | |
'alg' => 'RS256' | |
]; | |
$base64UrlHeader = base64url_encode(json_encode($header)); | |
$now = time(); | |
$payload = [ | |
'iat' => $now - 60, | |
'exp' => $now + 600, | |
'iss' => '241477' | |
]; | |
$base64UrlPayload = base64url_encode(json_encode($payload)); | |
// When you generate your GitHub App's private key, you should have been prompted to save your .pem. | |
// If you didn't, you will need to generate another private key and delete the old one. In this example, | |
// I stored my .pem file a directory above DOCUMENT_ROOT so that in normal configurations others won't be | |
// able to access it. | |
$key = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/../your-gh-app.2022-02-22.private-key.pem'); | |
openssl_sign("$base64UrlHeader.$base64UrlPayload", $signature, $key, 'sha256WithRSAEncryption'); | |
$base64UrlSignature = base64url_encode($signature); | |
$jwt = "$base64UrlHeader.$base64UrlPayload.$base64UrlSignature"; | |
echo $jwt; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment