苹果授权登录 jwt node 解码

苹果授权登录 jwt node 解码

const jwt_decode = require('jwt-decode')
const NodeRSA = require('node-rsa');
const axios = require('axios');
const jwt = require('jsonwebtoken');

let token = 'ios端返回的 identityToken'

// 获取公钥
async function getApplePublicKey(token) {
  let res = await axios.request({
    method: "GET",
    url: "https://appleid.apple.com/auth/keys",
  })

  let decodedHeader = jwt_decode(token, { header: true }); // 获取对应的 header 如 { kid: 'YuyXoY', alg: 'RS256' }
  let key = res.data.keys.filter(f => f.kid === decodedHeader.kid)[0] // 通过 header 匹配公钥

  const pubKey = new NodeRSA();
  pubKey.importKey({ n: Buffer.from(key.n, 'base64'), e: Buffer.from(key.e, 'base64') }, 'components-public');
  return pubKey.exportKey(['public']);
};

// 通过公钥和RS256算法解密id_token
async function verifyIdToken(id_token) {
  const applePublicKey = await getApplePublicKey(id_token);
  const jwtClaims = jwt.verify(id_token, applePublicKey, { algorithms: 'RS256' });
  return jwtClaims;
};

verifyIdToken(token).then(res => {
  console.log(res)
  /**
{
  iss: 'https://appleid.apple.com', 颁发者注册声明标识颁发身份令牌的委托人,固定值
  aud: '对应的 AppId',
  exp: 过期时间
  iat: Apple 在 UTC 中发布身份令牌的时间
  sub: '用户对应应用的唯一标识符',
  c_hash: '哈希值',
  email: '用户邮箱',
  email_verified: 'true', 否验证了电子邮件
  auth_time: 1631001894,
  nonce_supported: true 是否支持 nonce
}
 */
// 默认有效时间为一天
// 过期返回 UnhandledPromiseRejectionWarning: TokenExpiredError: jwt expired
})
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值