JWT token for API not working in Python

Hi,

I'm writing a Python script to automate the extraction of reports from the Apple App Store Connect API, more specifically the SALES and the SUBSCRIBER reports, using Airflow.

The code passed the tests but when implemented in production, the Airflow task calling the Apple App Store Connect API fails, due to a 401 unauthorized error. This suggests there is some issue with the authentication (JWT / bearer token) part.

I tried various solutions but none of them worked.

Here is part of the code, at this point I don't really understand what is wrong.

Any help in identifying the issue is appreciated:

class AppStore(ReadApi):

    def __init__(
        self,
        api_secret_conf: dict,
        vendor_number: int,
        **kwargs,
    ):
        ReadApi.__init__(self, **kwargs)
        self.kid = api_secret_conf["kid"]  # Key ID
        self.iss = api_secret_conf["iss"]  # Issuer ID
        self.private_key = api_secret_conf["private_key"]  # Private key
        self.vendor_number = int(vendor_number)

    def generate_jwt_token(self):
        # Generate jwt token required by App Store Connect API
        # Each token is valid for 20 minutes (max time allowed)
        jwt_headers = {"alg": "ES256", "kid": self.kid, "typ": "JWT"}
        jwt_payload = {
            "iss": self.iss,
            "iat": int(time.time()),
            "exp": int(time.time()) + 60 * 20,
            "aud": "appstoreconnect-v1",
        }

        private_key = self.private_key.encode("utf8")
        token = jwt.encode(
            jwt_payload, private_key, algorithm="ES256", headers=jwt_headers
        )
        decoded_token = token.decode("utf-8")
        return decoded_token
JWT token for API not working in Python
 
 
Q