我正在玩弄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文件,它的工作。