I am trying to connect to Apple Store Connect through their REST API's. Though this was working a few days ago, but i am not able to figure out why it's stopped working. Now i am not able to get past being authenticated i.e. each request i make the server response is a 401. Am i missing something?
What i do:
- Generate the JWT (i use SwiftJWT library)
- Create URLRequest object with the relevant headers set
- Make a call to the API using the created URLRequest
Generating the JWT:
func generateJWT() -> String {
var signedJWT = ""
let pathToKey = URL(fileURLWithPath: "AuthKey.p8")
// Header - alg is automatically set to ES256, and so is typ is set to JWT
let header = Header(kid: "********")
// Represents the payload being used to generate the JWT
let claim = MyClaims(iss: "***", exp: Date(timeIntervalSinceNow: 3600), aud: "appstoreconnect-v1")
var jwt = JWT(header: header, claims: claim)
do {
let privateKey: Data = try Data(contentsOf: pathToKey, options: .alwaysMapped)
let jwtSigner = JWTSigner.es256(privateKey: privateKey)
signedJWT = try jwt.sign(using: jwtSigner)
} catch {
print("There was an error getting the key...\(error)")
}
return signedJWT
}
Then i create a URLRequest with all the required headers:
func createRequest(with jwt: String) -> URLRequest? {
guard let url = URL(string: "https://api.appstoreconnect.apple.com/v1/users") else {
print("Ugh! Something went wrong with the URL provided...")
return nil
}
var request = URLRequest(url: url)
request.setValue(jwt, forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
return request
}
Then i make the request:
func performRequest(request: URLRequest) -> Bool {
var status = false
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode([String:String].self, from: data) {
// For this sample project we do nothing other than celebrate
// everything is good, so we can exit
status = true
return
}
}
// if we're still here it means there was a problem
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
print("Fetch failed: \(String(describing: response))")
status = false
}.resume()
return status
}
Response
Fetch failed: Optional(<NSHTTPURLResponse: 0x600002ac95e0> { URL: https://api.appstoreconnect.apple.com/v1/users } { Status Code: 401, Headers {
"Content-Length" = (
350
);
"Content-Type" = (
"application/json"
);
Date = (
"Fri, 09 Jul 2021 15:47:27 GMT"
);
Server = (
"daiquiri/3.0.0"
);
"Strict-Transport-Security" = (
"max-age=31536000; includeSubDomains"
);
"x-apple-jingle-correlation-key" = (
XXXXXXXXXXX
);
"x-daiquiri-instance" = (
"daiquiri:38493001:pv50p00it-hyhk12043901:7987:21HOTFIX14"
);
} })
Is there anything i'm doing incorrectly or missing?