首先下文的一切都是对下面大佬的模仿,我仅作总结,如侵权请联系删除
1.在python坏境下运行下面代码
import requests
import time
import json
# Step 1: 获取device_code和user_code
data = {
"client_id": "Iv1.b507a08c87ecfe98",
"scope": "read:user"
}
response = requests.post('https://github.com/login/device/code', headers={'Accept': 'application/json', 'Content-Type': 'application/json'}, data=json.dumps(data))
result = response.json()
device_code = result['device_code']
user_code = result['user_code']
print("Your user code is: ", user_code)
print("Please go to https://github.com/login/device and enter this user code.")
# Step 2: 登录github验证
# 这一步需要用户手动执行
# Step 3: 查询获取访问令牌
data = {
"client_id": "Iv1.b507a08c87ecfe98",
"device_code": device_code,
"grant_type": "urn:ietf:params:oauth:grant-type:device_code"
}
# 由于可能需要一些时间才能验证成功,所以这里使用一个循环来定期检查
while True:
response = requests.post('https://github.com/login/oauth/access_token', headers={'Accept': 'application/json', 'Content-Type': 'application/json'}, data=json.dumps(data))
result = response.json()
if 'access_token' in result:
print("Your access token is: ", result['access_token'])
break
elif 'error' in result:
if result['error'] == 'authorization_pending':
print("Authorization still pending. Will check again in 10s.")
time.sleep(10)
else:
print("Error: ", result['error'])
break
else:
print("Unexpected response: ", result)
break
2.手动打开
https://github.com/login/device
该网址,填写控制台打印出的验证码