后端验证苹果提供了两种验证方式:
一种是基于JWT identityToken的算法验证,另外一种是基于授权码的验证。
这里给出JW验证方式代码:
let axios = require('axios');
let NodeRSA = require('node-rsa');
let jwt = require('jsonwebtoken');
// 验证access token
const getApplePublicKey = async (header) => {
let res = await axios.request({
method: "GET",
url: "https://appleid.apple.com/auth/keys",
});
// console.log(res.data.keys);
let key = res.data.keys.filter(f => f.kid === header.kid)[0]; // 通过 header 匹配公钥
if (!key) {
return null;
}
const pubKey = new NodeRSA();
pubKey.importKey({n: Buffer.from(key.n, 'base64'), e: Buffer.from(key.e, 'base64')}, 'components-public');
return pubKey.exportKey(['public']);
};
let verifyIdToken = async (idToken) => {
let decoded = jwt.decode(idToken, {complete: true}); // 获取对应的 header 如 { kid: 'YuyXoY', alg: 'RS256' }
if (!decoded || !decoded.header) {
return null;
}
const applePublicKey = await getApplePublicKey(decoded.header);
try {
if (!applePublicKey) {
return null;
}
return jwt.verify(idToken, applePublicKey, {algorithms: decoded.header.alg});
} catch (e) {
console.log("error", e.toString());
return null;
}
};
let idToken = ""; // todo 这里填写客服端请求获得的 identityToken
verifyIdToken(idToken).then((jwtClaims) => {
// 这里判断 jwtClaims 为 null 验证失败, 存在且 jwtClaims.sub等于客户端发送的userId 则验证成功。
});