我正在玩弄oauth2以更好地理解它。出于这个原因,我已经安装了应该充当第三方应用程序的offlineimap。我在stackexchange上找到了一个很好的方式来读取加密凭证。如何通过Python为offlinemap使用gpg加密的oauth文件
基于链接的帖子我已经修改/复制下面的python脚本:
import subprocess
import os
import json
def passwd(file_name):
acct = os.path.basename(file_name)
path = "/PATHTOFILE/%s" % file_name
args = ["gpg", "--use-agent", "--quiet", "--batch", "-d", path]
try:
return subprocess.check_output(args).strip()
except subprocess.CalledProcessError:
return ""
def oauthpasswd(acct, key):
acct = os.path.basename(acct)
path = "/PATHTOFILE/%s_oauth2.gpg" % acct
args = ["gpg", "--use-agent", "--quiet", "--batch", "-d", path]
try:
return str(json.loads(subprocess.check_output(args).strip())['installed'][key])
except subprocess.CalledProcessError:
return ""
def prime_gpg_agent():
ret = False
i = 1
while not ret:
ret = (passwd("prime.gpg") == "prime")
if i > 2:
from offlineimap.ui import getglobalui
sys.stderr.write("Error reading in passwords. Terminating.\n")
getglobalui().terminate()
i += 1
return ret
prime_gpg_agent()
在相应offlineimaprc文件叫我用正确的参数的函数:
oauth2_client_id = oauthpasswd('gmail', 'client_id')
oauth2_client_secret = oauthpasswd('gmail', 'client_secret')
oauth2_request_url = https://accounts.google.com/o/oauth2/token
oauth2_refresh_token = passwd('gmail_rf_token.gpg')
请注意在本地文件中PATHTOFILE
设置正确。我所做的是从Google下载了包含oauth2凭证的JSON文件并对其进行了加密。我已将刷新令牌存储在单独的文件中。 但是,如果我跑offlineimap我得到一个验证错误:
ERROR: While attempting to sync account 'gmail'
('http error', 401, 'Unauthorized', <httplib.HTTPMessage instance at 0x7f488c214320>) (configuration is: {'client_secret': "oauthpasswd('gmail', 'client_secret')", 'grant_type': 'refresh_token', 'refresh_token': "passwd('gmail_rf_token.gpg')", 'client_id': "oauthpasswd('gmail', 'client_id')"})
我试着再检查的两个Python功能passwd
和oauthpasswd
输出在Python解释器。我得到所需的输出。更重要的是,我将python解释器中的函数输出复制到offlineimaprc配置文件,并且我能够同步到Gmail。这意味着当offlineimap执行文件时一定会出现错误,但我看不到有什么问题。
如果我只加密我的Gmail密码,一切正常。这意味着从Google下载的详细信息出现问题(client_id,client_secret和刷新令牌)。如上所述,这些值本身是正确的。我真的已经复制
oauthpasswd('gmail', 'client_id')
oauthpasswd('gmail', 'client_secret')
passwd('gmail_rf_token.gpg')
从python控制台到offlineimaprc文件,它的工作。