Thought it would be useful to add an example using Kitura SwiftJWT. This is based on creating a JWT for Apple’s App Store Connect API as described in WWDC18 Session 303 "Automating App Store Connect".
import Foundation
import SwiftJWT
let privateKeyId = "KI21S9DGKA"
let downloadsFolder = "/Users/johapp/Downloads"
let privateKeyPath = URL(fileURLWithPath: "\(downloadsFolder)/AuthKey_\(privateKeyId).p8")
let privateKey: Data = try Data(contentsOf: privateKeyPath, options: .alwaysMapped)
let header = Header(kid: privateKeyId)
struct MyClaims: Claims {
let issuerId: String
let audience: String
let expiryTime: Date
}
let twentyMinutes = Date(timeIntervalSinceNow: 3600)
let claims = MyClaims(issuerId: "1623hdgak-8daf-98db-l1xa-d9aj2vxj2a",
audience: "appstoreconnect-v1",
expiryTime: twentyMinutes)
var jwt = JWT(header: header, claims: claims)
let jwtSigner = JWTSigner.es256(privateKey: privateKey)
let signedJwt = try jwt.sign(using: jwtSigner)
print(signedJwt)
To try out the above, copy paste the signedJwt
output into Terminal:
curl https://api.appstoreconnect.apple.com/v1/apps --Header "Authorization: Bearer copyPasteSignedJwtOutputHere”
For those interested in the App Store Connect API, something one must pay particular attention to is the expiry time. For this I must thank the poster on Connecting to Apple Store Connect using Swift (with SwiftJWT) and REST API's - failing with 401
That is, exceeding Apple’s expiry time limit - of twenty minutes - will result in a misleading 401
NOT_AUTHORIZED
error.