Skip to content

Instantly share code, notes, and snippets.

@Ayubur
Created February 25, 2025 16:43
Show Gist options
  • Save Ayubur/4a800378b13be30e9f1b27f1a31a60d9 to your computer and use it in GitHub Desktop.
Save Ayubur/4a800378b13be30e9f1b27f1a31a60d9 to your computer and use it in GitHub Desktop.
Utility function to validate apple identity token and return back apple userid using apple identity token and userid
const APPLE_KEYS_URL = "https://appleid.apple.com/auth/keys";
const APPLE_ISS_URL = "https://appleid.apple.com";
const validateAppleIdentityToken = async (identityToken, appleUserId) => {
const { data } = await axios.get(APPLE_KEYS_URL);
const applePublicKey = data;
const tokenDecodedHeader = jwtDecode(identityToken, { header: true });
const kid = tokenDecodedHeader.kid;
const sharedKid = applePublicKey.keys.filter((x) => x["kid"] === kid)[0]?.[
"kid"
];
const client = new JwksClient({
jwksUri: APPLE_KEYS_URL,
});
const key = await client.getSigningKey(sharedKid);
const signingKey = key.getPublicKey();
try {
const response = jwt.verify(identityToken, signingKey);
if (response.iss !== APPLE_ISS_URL) {
throw new Error("Invalid Apple Identity token");
}
return { appleId: appleUserId };
} catch (e) {
throw new Error("Invalid Apple Identity token");
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment