Skip to content

Instantly share code, notes, and snippets.

@davidhariri
Created October 12, 2019 18:14
Show Gist options
  • Save davidhariri/b053787aabc9a8a9cc0893244e1549fe to your computer and use it in GitHub Desktop.
Save davidhariri/b053787aabc9a8a9cc0893244e1549fe to your computer and use it in GitHub Desktop.
Code required to verify Sign in with app-made Apple JWT tokens server-side in Python
import jwt
from jwt.algorithms import RSAAlgorithm
import requests
from time import time
import json
import os
APPLE_PUBLIC_KEY_URL = "https://appleid.apple.com/auth/keys"
APPLE_PUBLIC_KEY = None
APPLE_KEY_CACHE_EXP = 60 * 60 * 24
APPLE_LAST_KEY_FETCH = 0
class AppleUser(object):
def __init__(self, apple_id, email=None):
self.id = apple_id
self.email = email
self.full_user = False
if email is not None:
self.full_user = True
def __repr__(self):
return "<AppleUser {}>".format(self.id)
def _fetch_apple_public_key():
# Check to see if the public key is unset or is stale before returning
global APPLE_LAST_KEY_FETCH
global APPLE_PUBLIC_KEY
if (APPLE_LAST_KEY_FETCH + APPLE_KEY_CACHE_EXP) < int(time()) or APPLE_PUBLIC_KEY is None:
key_payload = requests.get(APPLE_PUBLIC_KEY_URL).json()
APPLE_PUBLIC_KEY = RSAAlgorithm.from_jwk(json.dumps(key_payload["keys"][0]))
APPLE_LAST_KEY_FETCH = int(time())
return APPLE_PUBLIC_KEY
def _decode_apple_user_token(apple_user_token):
public_key = _fetch_apple_public_key()
try:
token = jwt.decode(apple_user_token, public_key, audience=os.getenv("APPLE_APP_ID"), algorithm="RS256")
except jwt.exceptions.ExpiredSignatureError as e:
raise Exception("That token has expired")
except jwt.exceptions.InvalidAudienceError as e:
raise Exception("That token's audience did not match")
except Exception as e:
print(e)
raise Exception("An unexpected error occoured")
return token
def retrieve_user(user_token):
token = _decode_apple_user_token(user_token)
apple_user = AppleUser(token["sub"], token.get("email", None))
return apple_user
@fhdez
Copy link

fhdez commented Jun 12, 2020

Thanks for sharing!!, for other developers in testing data maybe got the error InvalidSignatureError('Signature verification failed',) is for the time lapse for the token expired 5min, so short to testing, we have to obtain a new token to tests without troubles.

@michaelotto
Copy link

Hm, does not work for me.

RSAAlgorithm.from_jwk(json.dumps(key_payload["keys"][0]))

returns a cryptography.hazmat.backends.openssl.rsa._RSAPublicKey object as the Apple Public Key, while jwt.decode expects a string as a public key. Is this a different version of jwt?

@emcas88
Copy link

emcas88 commented Jun 17, 2020

Hm, does not work for me.

RSAAlgorithm.from_jwk(json.dumps(key_payload["keys"][0]))

returns a cryptography.hazmat.backends.openssl.rsa._RSAPublicKey object as the Apple Public Key, while jwt.decode expects a string as a public key. Is this a different version of jwt?

You might have to install the 'cryptography' package: https://cryptography.io/en/latest/

@emcas88
Copy link

emcas88 commented Jun 17, 2020

Hm, does not work for me.

RSAAlgorithm.from_jwk(json.dumps(key_payload["keys"][0]))

returns a cryptography.hazmat.backends.openssl.rsa._RSAPublicKey object as the Apple Public Key, while jwt.decode expects a string as a public key. Is this a different version of jwt?

Yes is expecting a string so you have to convert to a string, im sharing the code:

apple_public_key_as_string = apple_public_key.public_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PublicFormat.SubjectPublicKeyInfo
            )

@michaelotto
Copy link

Thanks very much for your help. Installing 'cryptography' didn't help.

I had tried converting the public key to a string beforehand myself. It returns the error (when used with the Apple key):

jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.

Also, why does the above, unmodified code, work for you, but not for somebody else? Either the API call expects a structured object or a string, but not one thing for the one user and one thing for another.

I'm clueless here.

@emcas88
Copy link

emcas88 commented Jun 17, 2020

Thanks very much for your help. Installing 'cryptography' didn't help.

I had tried converting the public key to a string beforehand myself. It returns the error (when used with the Apple key):

jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.

Also, why does the above, unmodified code, work for you, but not for somebody else? Either the API call expects a structured object or a string, but not one thing for the one user and one thing for another.

I'm clueless here.

The original implementation didnt work for me, i had to to change a few things, i will try to modify later this code and push it when i have some time.

@michaelotto
Copy link

That would be very helpful, thank you!

@michaelotto
Copy link

I think I know why the exception above occurred - I wasn't testing with an actual Apple Token, but with a token that needed a symmetric secret for verification. Does anybody know where to get actual Apple signed JWT Tokens for testing?

@SailingSteve
Copy link

@emcas88 That is quite a teaser! "The original implementation didn't work for me, i had to to change a few things, i will try to modify later this code and push it when i have some time." Could you send your working version?

@SailingSteve
Copy link

I have spent more than a day on this, and need to ask a very basic question. The code/token that I get back from Sign in with Apple ("https://appleid.apple.com/auth/authorize?") via JavaScript is

ce328a54c58114324957c1994932b0856.0.nruqx.9wwNzKYMETQQlZF1UfrGOg

And api_jwt.py base64url_decode pads the header out to

header segment = b'ce328a54c58114324957c1994932b0856==='

And base64.py binascii.a2b_base64 tries to make a 64bit value out of that string of bytes, and throws a binascii.Error 'Invalid header padding'

This issue is so basic, I wonder if I am requesting the correct code/token from Apple?

@emcas88
Copy link

emcas88 commented Jul 13, 2020

import json  # pragma: no cover
import jwt   # pragma: no cover
from cryptography.hazmat.primitives import serialization    # pragma: no cover
from jwt.algorithms import RSAAlgorithm     # pragma: no cover

class AppleResolver(object):

    @classmethod
    def __get_right_public_key_info(cls, keys, unverified_header):
        for key in keys:
            if key['kid'] == unverified_header['kid']:
                return key

    @classmethod
    def authenticate(cls, access_token):

        import http.client

        apple_keys_host = 'appleid.apple.com'
        apple_keys_url = '/auth/keys'
        headers = {"Content-type": "application/json"}

        try:

            connection = http.client.HTTPSConnection(apple_keys_host, 443)
            connection.request('GET', apple_keys_url, headers=headers)
            response = connection.getresponse()

            keys_json = json.loads(response.read().decode('utf8'))
            connection.close()

            unverified_header = jwt.get_unverified_header(access_token)

            public_key_info = cls.__get_right_public_key_info(keys_json['keys'], unverified_header)

            apple_public_key = RSAAlgorithm.from_jwk(json.dumps(public_key_info))

            apple_public_key_as_string = apple_public_key.public_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PublicFormat.SubjectPublicKeyInfo
            )

            verified_payload = jwt.decode(access_token, apple_public_key_as_string, audience=config.APPLE_APP_ID, algorithm=public_key_info['alg'])

            return {'email': verified_payload['email']}

        except Exception as ex:
            raise AuthorizationException(AuthorizationSubcode.InvalidProviderToken) from ex

This is my code guys, ignore the exception part. Shoot me any questions if u like.

@michaelotto
Copy link

That's pretty much the solution I ended up with. It's even better than the original one, because it considers the 'kid' parameter for selecting the key, so if Apple one day decides to switch keys and supports an intermediate key, this will still work. The original post's solution won't.

@emcas88
Copy link

emcas88 commented Jul 13, 2020

That's pretty much the solution I ended up with. It's even better than the original one, because it considers the 'kid' parameter for selecting the key, so if Apple one day decides to switch keys and supports an intermediate key, this will still work. The original post's solution won't.

exactly !!

@SailingSteve
Copy link

SailingSteve commented Aug 5, 2020

Thank you @emcas88, it worked perfectly!

For other newbies:
audience=config.APPLE_APP_ID is a string like "us.wevote.webapp" that you need to configure somewhere

Also part of the verified_payload is the sub element that apple defines as "The subject registered claim identifies the principal that is the subject of the identity token. Since this token is meant for your application, the value is the unique identifier for the user."
The sub solves another issue that I have with repeated signins (from both ios and web) -- it allows us to match prior signins using other OAuth schemes -- which allows the end user to not lose all their data, when they switch to Sign in with Apple..

@shredding
Copy link

You are the light in the darkness surrounding everything related to apple sign in.

@ssi-anik
Copy link

If you want to know thoroughly. https://sarunw.com/posts/sign-in-with-apple-4/

@ldonjibson
Copy link

Thank you @emcas88, it worked perfectly!

For other newbies:
audience=config.APPLE_APP_ID is a string like "us.wevote.webapp" that you need to configure somewhere

Also part of the verified_payload is the sub element that apple defines as "The subject registered claim identifies the principal that is the subject of the identity token. Since this token is meant for your application, the value is the unique identifier for the user."
The sub solves another issue that I have with repeated signins (from both ios and web) -- it allows us to match prior signins using other OAuth schemes -- which allows the end user to not lose all their data, when they switch to Sign in with Apple..

Thanks for this ... it daved me another sleepless night.

Inaddition the

RSAAlgorithm.from_jwk(json.dumps(key_payload["keys"][0]))

I had to use for it to work

RSAAlgorithm.from_jwk(json.dumps(key_payload["keys"][1]))

if index zero doesnot work for you, you can try index one

@rcstanciu
Copy link

@ldonjibson

if index zero doesnot work for you, you can try index one

You should use the key that was used for encoding the payload (can be found in token's kid header). @emcas88 has pasted an example above.

@Jan-Jasek
Copy link

Thank you, was very helpful. This is what I used with python-jose[cryptography] instead of old PyJWT

import logging
import requests

from typing import Dict, Union, List
from fastapi import HTTPException
from jose import jwt, jwk, JWTError
from starlette import status

from modules.database.models.member_user import MemberUser
from services.user_service.domain.providers.apple.constants import AppleUtilConstants
from settings.secrets import APPLE_OAUTH2_WEB_CLIENT_ID

def validate_user(provider_id_token_jwt: str) -> Dict[str, str]:
    # Get public key set from Apple
    try:
        keys: Dict[str, List[Dict[str, str]]] = dict(requests.get(AppleUtilConstants.KEYS_URL.value).json())
    except Exception as error:
        logging.exception(repr(error))
        raise Exception("Unable to connect to Apple.")
    # Get headers of our id token
    headers = jwt.get_unverified_headers(token=provider_id_token_jwt)
    # Find matching public key based on the kid header
    public_key: Dict[str, str] = next(filter(lambda key: (key["kid"] == headers["kid"]), keys["keys"]))
    # Construct the actual public_key
    public_rsa_key = jwk.construct(public_key_set)
    try:
        decoded_id_token = dict(
            jwt.decode(
                token=provider_id_token_jwt,
                audience=APPLE_OAUTH2_WEB_CLIENT_ID,
                key=public_key,
                algorithms=["RS256"],
            )
        )
    except jwt.ExpiredSignatureError as error:
        logging.info(repr(error))
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Token has expired",
        )
    except JWTError as error:
        logging.info(repr(error))
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Unable to process given id_token",
        )
    except Exception as error:
        logging.exception(repr(error))
        raise Exception("An unexpected error occurred")

    return decoded_id_token

@nikiforoveee
Copy link

thank you, so match ! I loosed 2 days before found this solution !

@adlrwbr
Copy link

adlrwbr commented Jun 7, 2022

This thread is a godsend

@pythonwood
Copy link

pyjwt >= 2.0 diff from pyjwt == 1.7.1 options={"verify_exp": False}, algorithms=["RS256"],

change log

.. code:: python

import jwt
from jwt import PyJWKClient

token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik5FRTFRVVJCT1RNNE16STVSa0ZETlRZeE9UVTFNRGcyT0Rnd1EwVXpNVGsxUWpZeVJrUkZRdyJ9.eyJpc3MiOiJodHRwczovL2Rldi04N2V2eDlydS5hdXRoMC5jb20vIiwic3ViIjoiYVc0Q2NhNzl4UmVMV1V6MGFFMkg2a0QwTzNjWEJWdENAY2xpZW50cyIsImF1ZCI6Imh0dHBzOi8vZXhwZW5zZXMtYXBpIiwiaWF0IjoxNTcyMDA2OTU0LCJleHAiOjE1NzIwMDY5NjQsImF6cCI6ImFXNENjYTc5eFJlTFdVejBhRTJINmtEME8zY1hCVnRDIiwiZ3R5IjoiY2xpZW50LWNyZWRlbnRpYWxzIn0.PUxE7xn52aTCohGiWoSdMBZGiYAHwE5FYie0Y1qUT68IHSTXwXVd6hn02HTah6epvHHVKA2FqcFZ4GGv5VTHEvYpeggiiZMgbxFrmTEY0csL6VNkX1eaJGcuehwQCRBKRLL3zKmA5IKGy5GeUnIbpPHLHDxr-GXvgFzsdsyWlVQvPX2xjeaQ217r2PtxDeqjlf66UYl6oY6AqNS8DH3iryCvIfCcybRZkc_hdy-6ZMoKT6Piijvk_aXdm7-QQqKJFHLuEqrVSOuBqqiNfVrG27QzAPuPOxvfXTVLXL2jek5meH6n-VWgrBdoMFH93QEszEDowDAEhQPHVs0xj7SIzA"
kid = "NEE1QURBOTM4MzI5RkFDNTYxOTU1MDg2ODgwQ0UzMTk1QjYyRkRFQw"
url = "https://dev-87evx9ru.auth0.com/.well-known/jwks.json"

jwks_client = PyJWKClient(url)
signing_key = jwks_client.get_signing_key_from_jwt(token)

data = jwt.decode(
    token,
    signing_key.key,
    algorithms=["RS256"],
    audience="https://expenses-api",
    options={"verify_exp": False},
)
print(data)

@scorpioailabs
Copy link

scorpioailabs commented Sep 18, 2024

amazing thank you so much! this works, with a bit of tweaking for jose:

from jose import jwt, JWTError
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
# method to validate apple sign in using id_token param
#....
        try:
            public_key_from_apple  = _fetch_apple_public_key()
            apple_public_key_as_string = public_key_from_apple.public_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PublicFormat.SubjectPublicKeyInfo
            )
        try:
            decoded = jwt.decode(id_token_str, apple_public_key_as_string, algorithms="RS256", audience=os.getenv("APPLE_CLIENT_ID"))
        except Exception as e:
            raise Exception(e)

@montasaurus
Copy link

I hit signature verification issues since it's assuming the first key is the one used to sign the token. Wrote an updated version here that you can use as a CLI to test with as well: https://gist.github.com/montasaurus/6376b15f334d93262190a3de50fd0716

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment