apple id 后端验证 django

import time
import jwt
import requests
import json
from jwt.algorithms import RSAAlgorithm
from django.utils import timezone
from datetime import timedelta
import ******.settings

data_list = {
    "errMsg": "getUserInfo:ok",
    "userInfo": {
        "openId": "******",
        "fullName": {},
        "authorizationCode": "******",
        "identityToken": "******",
        "realUserStatus": 1
    }
}
timezone.now()
TEAM_ID = '******'
BUNDLE_ID = '******'
ALG = 'ES256'
KID = '******'
CODE_URL = 'https://appleid.apple.com/auth/token'
GRAND_TYPE = 'authorization_code'
AUD_URL = 'https://appleid.apple.com'
AUD_WS = 'appleid.apple.com'
TOKEN_URL = 'https://appleid.apple.com/auth/keys'
PRIVATE_KEY = """-----BEGIN PRIVATE KEY-----
******
-----END PRIVATE KEY-----
"""
# header = {"alg": "ES256", 'kid': KID}
header = {"alg": "ES256", 'kid': KID}
payload = {
    'iss': TEAM_ID,
    'iat': timezone.now(),
    'exp': timezone.now() + timedelta(days=180),
    'aud': AUD_URL,
    'sub': BUNDLE_ID
}
client_secret = jwt.encode(payload, PRIVATE_KEY, headers=header)


# print(type(client_secret))
def post_datas(code):
    post_data = {
        'client_id': BUNDLE_ID,
        'client_secret': client_secret,
        # 'code': data_list['userInfo']['authorizationCode'],
        'code': code,
        'grant_type': GRAND_TYPE,
    }

    login_req = requests.post(url=CODE_URL, data=post_data,
                              headers={"Content-Type": "application/x-www-form-urlencoded"}
                              )
    if login_req.status_code == 200:
        pass
    else:
        post_data['grant_type'] = 'refresh_token'
        post_data['refresh_token'] = '******'
        post_data['redirect_uri'] = '******'
    key_req = requests.get(TOKEN_URL).json()
    # 从data那里拿到token的加密方式
    head = jwt.get_unverified_header(login_req.json()['id_token'])
    token_key = head['kid']
    # 找到相对应的公钥,一般会发布多个公钥
    for pub_key in key_req['keys']:

        if pub_key['kid'] == token_key:
            key_core = json.dumps(pub_key)
            # 打包公钥
            key = RSAAlgorithm.from_jwk(key_core)
            alg = pub_key['alg']
            break
    else:
        print('Unable to find public key')
        return None
    # 使用公钥来解密
    claims = jwt.decode(login_req.json()['id_token'].encode("utf-8"), key=key, verify=True, algorithms=[alg],
                        audience=BUNDLE_ID)
    return claims['sub']
print(post_datas(****))

  

posted @ 2021-11-16 15:13  Lilinpei  阅读(88)  评论(0编辑  收藏  举报