如何通过Python使用GPG加密的OAuth文件来进行OfflineIMAP操作

6

我正在尝试使用oauth2来更好地理解它。因此,我安装了offlineimap作为第三方应用程序。在stackexchange上,我找到了一种很好的方法来读取加密凭据。

基于链接的帖子,我修改/复制了以下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解释器中检查passwdoauthpasswd这两个Python函数的输出。我得到了期望的输出。更重要的是,我把函数输出从Python解释器复制到了offlineimaprc配置文件中,并且我能够同步到Gmail。这意味着当offlineimap执行该文件时一定出了问题,但我却看不出错在哪里。
如果我只加密我的Gmail密码,一切都正常。这意味着从Google下载的细节信息(client_id、client_secret和refresh token)有些问题。正如上面所指出的,这些值本身是正确的。我确实复制了输出结果。
oauthpasswd('gmail', 'client_id')
oauthpasswd('gmail', 'client_secret')
passwd('gmail_rf_token.gpg')

我将Python控制台中的内容复制到了offlineimaprc文件中并成功运行。

1个回答

1
问题出在这里。根据answer,offlineimap不允许加密offlinemaprc文件中的所有密钥。这就是为什么Python函数从未被评估并且错误的字符串被传递的原因。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接