本文主要是介绍苹果账号登录后端验证两种方式 python2,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import json
import jwt
import requests
import json
import base64def 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,signdef 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_codeprint r.json()if r.status_code != 200:returnrjson = 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']breakif 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,0for 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_backendfrom cryptography.hazmat.primitives import serialization,hashesfrom 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',etoken = ""auth_apple_by_keys(token)
相关链接 : https://www.jianshu.com/p/655972b0e7da
这篇关于苹果账号登录后端验证两种方式 python2的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!