Created
November 7, 2018 01:21
-
-
Save jdgomeza/f86e0ce4e82cd0bea3ce5830b509b834 to your computer and use it in GitHub Desktop.
Groovy script to Create signed JSON Web Tokens (JWT) for App Store Connect API
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
@Grab(group='io.jsonwebtoken', module='jjwt-api', version='0.10.5') | |
@Grab(group='io.jsonwebtoken', module='jjwt-impl', version='0.10.5') | |
@Grab(group='io.jsonwebtoken', module='jjwt-orgjson', version='0.10.5') | |
import io.jsonwebtoken.* | |
import java.security.PrivateKey | |
import java.util.Base64 | |
import java.util.Base64.Decoder | |
import java.nio.charset.StandardCharsets | |
import java.security.interfaces.ECPrivateKey | |
import java.security.KeyFactory | |
import java.security.NoSuchAlgorithmException | |
import java.security.spec.PKCS8EncodedKeySpec | |
// Generating Tokens for API Requests | |
// https://developer.apple.com/documentation/appstoreconnectapi/generating_tokens_for_api_requests | |
def exp = (System.currentTimeMillis() / 1000 + 1200).trunc() | |
//20 minutes from now | |
//JWT Payload (update with your Issuer ID) | |
String jsonString = """{"iss":"57246542-96fe-1a63-e053-0824d011072a","exp":${exp},"aud":"appstoreconnect-v1"}"""; | |
//Content of the AuthKey_2X9R4HXF34.p8 | |
/* | |
-----BEGIN PRIVATE KEY----- | |
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg74+aaeYnqEIewDn8 | |
Xh0rQXaQqAHSLGDyL9fV0p1hhxGgCgYIKoZIzj0DAQehRANCHOTEUjCMi4Vt7JGZ | |
jsRP1zF765oerCqfvHZYGqSeJl8AmK0awchcqAaMlw7hROoA2MToqx+llo2p9lZC | |
QYbeerau | |
-----END PRIVATE KEY----- | |
*/ | |
//Key concatenated in a single line | |
//You better not hard code this key | |
def base64EncodedPrivateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg74+aaeYnqEIewDn8Xh0rQXaQqAHSLGDyL9fV0p1hhxGgCgYIKoZIzj0DAQehRANCHOTEUjCMi4Vt7JGZjsRP1zF765oerCqfvHZYGqSeJl8AmK0awchcqAaMlw7hROoA2MToqx+llo2p9lZCQYbeerau" | |
ECPrivateKey signingKey | |
Base64.Decoder dec= Base64.getDecoder(); | |
keyBytes = dec.decode(base64EncodedPrivateKey.getBytes(StandardCharsets.US_ASCII)); | |
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); | |
KeyFactory keyFactory = KeyFactory.getInstance("EC"); | |
signingKey = keyFactory.generatePrivate(keySpec); | |
//Notice you don't need to encode the header nor the payload | |
String jwtToken = Jwts.builder() | |
//JWT Header | |
.setHeaderParam("typ","JWT") | |
.setHeaderParam("alg","ES256") | |
.setHeaderParam("kid","2X9R4HXF34") //UPDATE with your Key Identifier | |
.setPayload(jsonString) | |
.signWith(SignatureAlgorithm.ES256, signingKey) | |
.compact(); | |
print jwtToken |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment