import json
import jwt
import requests
import json
import base64
def decode_jwt(jwt_token):
try:
header,payload,sign = jwt_token.split('.')
except:
return {},{},""
header = json.loads(base64.urlsafe_b64decode(header + '===')) # 可能需要调整填充
payload = json.loads(base64.urlsafe_b64decode(payload + '===')) # 可能需要调整填充
return header,payload,sign
def auth_apple_by_token(client_id,client_secret,code):
"""
使用token方式
"""
url = "https://appleid.apple.com/auth/token"
params = {
'client_id':client_id,
'client_secret':client_secret,
'code':code,
'grant_type':"authorization_code",
}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
r = requests.post(url,data=params,headers=headers)
print r.status_code
print r.json()
if r.status_code != 200:
return
rjson = r.json()
id_token,access_token = rjson['id_token'],rjson['access_token']
header,payload,sign = decode_jwt(id_token)
def auth_apple_by_keys(id_token):
"""
使用keys 方式
"""
header,payload,sign = decode_jwt(id_token)
url = "https://appleid.apple.com/auth/keys"
r = requests.get(url)
keys = r.json()['keys']
n,e = '',''
for x in keys:
if x['kid'] == header['kid']:
n,e = x['n'],x['e']
break
if not n:
n = keys[0]['n']
e = keys[0]['e']
n_bytes = base64.urlsafe_b64decode(str(n)+"===")
e_bytes = base64.urlsafe_b64decode(str(e)+"===")
n,e = 0,0
for byte in e_bytes:
e = (e << 8) | ord(byte)
for byte in n_bytes:
n = (n << 8) | ord(byte)
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization,hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
#构建公钥
public_key = rsa.RSAPublicNumbers(e, n).public_key(default_backend())
# 如果需要,可以将公钥序列化为PEM格式
pem = public_key.public_bytes(serialization.Encoding.PEM,serialization.PublicFormat.SubjectPublicKeyInfo)
#print(pem)
try:
decoded = jwt.decode(id_token, key=pem, algorithms=['RS256'],verify=True,audience=payload['aud'])
print 'valid'
except Exception as e:
print 'invalid'
# try:
# public_key.verify(sign,id_token,padding.PKCS1v15(),hashes.SHA256())
# print 'valid'
# except Exception as e:
# print 'invalid',e
token = ""
auth_apple_by_keys(token)
苹果账号登录后端验证两种方式 python2
于 2024-09-06 16:39:58 首次发布