401 response for JWT token with Python (Django)

Hi everyone,

I've been trying to connect to the appstoreconnect API following the provided documentation.

I'm using Python, so I've tried several packages, and all of them give the same 401 response with the obtained token:

Code Block python
from django.utils import timezone
import jwt
def open_file(filename):
with open(filename, 'rb') as myfile:
data = myfile.read()
return data
def get_apple_token():
expiration_date = timezone.now() + timedelta(minutes=15)
timestamp = expiration_date.strftime('%s')
header = {
"alg": "ES256",
"kid": APPSTORE_KEY,
"typ": "JWT"
}
payload = {
"iss": APPSTORE_ISSUE,
"exp": timestamp,
"aud": "appstoreconnect-v1"
}
private_key = open_file(APPSTORE_KEY_PATH)
encoded = jwt.encode(payload, private_key, algorithm="ES256", headers=header)
print(encoded)

So I'm trying to use the generated token in a request, with postman or curl

Code Block bash
curl -v -H 'Authorization: Bearer [signed token]' "https://api.appstoreconnect.apple.com/v1/apps"


Whatever package I try for the signature (I've tried jwt, jose and jwcrypto) I get the same response:

Code Block json
{
"errors": [
{
"status": "401",
"code": "NOT_AUTHORIZED",
"title": "Authentication credentials are missing or invalid.",
"detail": "Provide a properly configured and signed bearer token, and make sure that it has not expired. Learn more about Generating Tokens for API Requests https://developer.apple.com/go/?id=api-generating-tokens"
}
]
}


Anyone having similar issues or spotting anything I may be missing?

Thank you very much!

Answered by dbe in 672190022
Hi,

In case anyone is having a similar issue, timestamp must be an int

Code Block python
expiration_date = timezone.now() + timedelta(minutes=15)
timestamp = int(expiration_date.strftime('%s'))


That solved it :)

Accepted Answer
Hi,

In case anyone is having a similar issue, timestamp must be an int

Code Block python
expiration_date = timezone.now() + timedelta(minutes=15)
timestamp = int(expiration_date.strftime('%s'))


That solved it :)

401 response for JWT token with Python (Django)
 
 
Q