Skip to content

Instantly share code, notes, and snippets.

@edinnen
Last active December 14, 2021 17:54
Show Gist options
  • Save edinnen/af35013e9d27e21cfa44f4ad3f09ced9 to your computer and use it in GitHub Desktop.
Save edinnen/af35013e9d27e21cfa44f4ad3f09ced9 to your computer and use it in GitHub Desktop.
Generate a signed JWT for authenticating Sign in With Apple user transfer requests
/* eslint-disable no-console */
const jwt = require('jsonwebtoken');
const fs = require('fs');
let bundleId, teamId, keyId, keyPath;
const SIX_MONTH_EXPIRY = Math.floor(Date.now() / 1000) + 86400 * 180;
// generateToken is a helper function to generate an ES256 JWT token.
function generateToken(bundleId, teamId, pk, exp, keyid) {
try {
const claims = {
iss: teamId,
iat: Math.floor(Date.now() / 1000),
exp,
aud: 'https://appleid.apple.com',
sub: bundleId
};
return jwt.sign(claims, pk, {
algorithm: 'ES256',
keyid
});
} catch (err) {
throw new Error(
'AppleAuth Error - Error occurred while signing: ' + err
);
}
}
// Process provided arguments
const args = process.argv.slice(2);
args.forEach((arg, i) => {
if (arg === '--bundleId')
bundleId = args[i + 1];
if (arg === '--teamId')
teamId = args[i + 1];
if (arg === '--keyId')
keyId = args[i + 1];
if (arg === '--keyPath')
keyPath = args[i + 1];
});
// Require all arguments
if (!(bundleId && teamId && keyId && keyPath)) {
console.log('Please provide all the required arguments. --bundleId, --teamId, --keyId, --keyPath');
process.exit(1);
}
// Load the private key
const privateKey = fs.readFileSync(keyPath);
// Generate the token and print to console
const token = generateToken(bundleId, teamId, privateKey, SIX_MONTH_EXPIRY, keyId);
console.log(`\x1b[36m\nJWT for service \x1b[32m${bundleId}\x1b[36m owned by team \x1b[32m${teamId}\x1b[36m signed with key \x1b[32m${keyId}\x1b[36m is:\n\n\x1b[40m\x1b[31m${token}\x1b[0m`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment