我有一个适用于 Google 邮件的 IMAP 客户端,但它最近停止工作了。我认为问题是 gmail 不再允许 TTL 用户名/密码登录,但现在需要 OAuth2.0。
我想知道更改下面示例的最佳方法,以便我的扭曲 IMAP 客户端使用 OAuth2.0 进行身份验证。 (如果可能的话,在没有 Google API 包的情况下这样做。)
使用用户名/密码登录的示例(不再有效)
class AriSBDGmailImap4Client(imap4.IMAP4Client):
'''
client to fetch and process SBD emails from gmail. the messages
contained in the emails are sent to the AriSBDStationProtocol for
this sbd modem.
'''
def __init__(self, contextFactory=None):
imap4.IMAP4Client.__init__(self, contextFactory)
@defer.inlineCallbacks
def serverGreeting(self, caps):
# log in
try:
# the line below no longer works for gmail
yield self.login(mailuser, mailpass)
try:
yield self.uponAuthentication()
except Exception as e:
uponFail(e, "uponAuthentication")
except Exception as e:
uponFail(e, "logging in")
# done. log out
try:
yield self.logout()
except Exception as e:
uponFail(e, "logging out")
@defer.inlineCallbacks
def uponAuthentication(self):
try:
yield self.select('Inbox')
try:
# read messages, etc, etc
pass
except Exception as e:
uponFail(e, "searching unread")
except Exception as e:
uponFail(e, "selecting inbox")
我为这个客户建立了一个简单的工厂。它通过将 reactor.connectSSL 与 Google 邮件的主机 url 和端口一起使用来启动。
我已按照 https://developers.google.com/gmail/api/quickstart/quickstart-python 中的说明进行操作对于“已安装的应用程序”(但我不知道这是否是正确的选择)。我可以成功运行他们的“quickstart.py”示例。
我快速而肮脏的尝试(不起作用)
@defer.inlineCallbacks
def serverGreeting(self, caps):
# log in
try:
#yield self.login(mailuser, mailpass)
flow = yield threads.deferToThread(
oauth2client.client.flow_from_clientsecrets,
filename=CLIENT_SECRET_FILE,
scope=OAUTH_SCOPE)
http = httplib2.Http()
credentials = yield threads.deferToThread( STORAGE.get )
if credentials is None or credentials.invalid:
parser = argparse.ArgumentParser(
parents=[oauth2client.tools.argparser])
flags = yield threads.deferToThread( parser.parse_args )
credentials = yield threads.deferToThread(
oauth2client.tools.run_flow,
flow=flow,
storage=STORAGE,
flags=flags, http=http)
http = yield threads.deferToThread(
credentials.authorize, http)
gmail_service = yield threads.deferToThread(
apiclient.discovery.build,
serviceName='gmail',
version='v1',
http=http)
self.state = 'auth'
try:
yield self.uponAuthentication()
except Exception as e:
uponFail(e, "uponAuthentication")
except Exception as e:
uponFail(e, "logging in")
# done. log out
try:
yield self.logout()
except Exception as e:
uponFail(e, "logging out")
我基本上只是将“quickstart.py”复制到 serverGreeting 中,然后尝试将客户端状态设置为“auth”。
这样验证就好了,但是扭曲后无法选择收件箱:
[AriSBDGmailImap4Client (TLSMemoryBIOProtocol),client] FAIL: Unknown command {random gibberish}
随机乱码有字母和数字,每次选择收件箱命令失败时都不同。
感谢您的帮助!
最佳答案
经过大量阅读和测试,我终于能够使用 OAuth2 实现 gmail 的有效登录。
一个重要的注意事项是使用“服务帐户”的两步过程对我来说不有效。我仍然不清楚为什么不能使用此过程,但服务帐户似乎无法访问同一帐户中的 gmail。即使服务帐户具有“可以编辑”权限并且启用了 Gmail API,也是如此。
有用的引用资料
使用概述 OAuth2 https://developers.google.com/identity/protocols/OAuth2
将 OAuth2 与“已安装的应用程序”一起使用的指南 https://developers.google.com/identity/protocols/OAuth2InstalledApp
设置帐户以将 OAuth2 与“已安装的应用程序”一起使用的指南 https://developers.google.com/api-client-library/python/auth/installed-app
没有完整 Google API 的 OAuth2 例程集合 https://code.google.com/p/google-mail-oauth2-tools/wiki/OAuth2DotPyRunThrough
第 1 步 - 获取 Google 客户端 ID
用gmail账号登录到https://console.developers.google.com/
启动一个项目,启用 Gmail API 并为已安装的应用程序创建一个新的客户端 ID。说明在 https://developers.google.com/api-client-library/python/auth/installed-app#creatingcred
单击“下载 JSON”按钮并将此文件保存在公众无法访问的位置(因此可能不在代码存储库中)。
第 2 步 - 获取 Google OAuth2 Python 工具
从 https://code.google.com/p/google-mail-oauth2-tools/wiki/OAuth2DotPyRunThrough 下载 oauth2.py 脚本
第 3 步 - 获取授权 URL
使用第 2 步中的脚本获取允许您授权您的 Google 项目的 URL。
在终端中:
python oauth2.py --user={myaccount@gmail.com} --client_id={json 文件中的 client_id} --client_secret={json 文件中的 client_secret} --generate_oauth2_token
第四步——获取授权码
将第 3 步中的 URL 粘贴到您的浏览器中,然后单击“接受”按钮。
从网页复制代码。
将代码粘贴到终端中并按回车键。您将获得:
To authorize token, visit this url and follow the directions: https://accounts.google.com/o/oauth2/auth?client_id{...}
Enter verification code: {...}
Refresh Token: {...}
Access Token: {...}
Access Token Expiration Seconds: 3600
第 5 步 - 保存刷新 token
从终端复制刷新 token 并将其保存在某处。在这个例子中,我将它保存到一个 json 格式的文本文件中,键为“Refresh Token”。但它也可以保存到私有(private)数据库中。
确保刷新 token 不能被公众访问!
第 6 步 - 制作扭曲的身份验证器
这是 OAuth2 身份验证器的工作示例。它需要步骤 2 中的 oauth2.py 脚本。
import json
import oauth2
from zope.interface import implementer
from twisted.internet import threads
MY_GMAIL = {your gmail address}
REFRESH_TOKEN_SECRET_FILE = {name of your refresh token file from Step 5}
CLIENT_SECRET_FILE = {name of your cliend json file from Step 1}
@implementer(imap4.IClientAuthentication)
class GmailOAuthAuthenticator():
authName = "XOAUTH2"
tokenTimeout = 3300 # 5 mins short of the real timeout (1 hour)
def __init__(self, reactr):
self.token = None
self.reactor = reactr
self.expire = None
@defer.inlineCallbacks
def getToken(self):
if ( (self.token==None) or (self.reactor.seconds() > self.expire) ):
rt = None
with open(REFRESH_TOKEN_SECRET_FILE) as f:
rt = json.load(f)
cl = None
with open(CLIENT_SECRET_FILE) as f:
cl = json.load(f)
self.token = yield threads.deferToThread(
oauth2.RefreshToken,
client_id = cl['installed']['client_id'],
client_secret = cl['installed']['client_secret'],
refresh_token = rt['Refresh Token'] )
self.expire = self.reactor.seconds() + self.tokenTimeout
def getName(self):
return self.authName
def challengeResponse(self, secret, chal):
# we MUST already have the token
# (allow an exception to be thrown if not)
t = self.token['access_token']
ret = oauth2.GenerateOAuth2String(MY_GMAIL, t, False)
return ret
第 7 步 - 为协议(protocol)注册 Authenitcator
在 IMAP4ClientFactory 中:
def buildProtocol(self, addr):
p = self.protocol(self.ctx)
p.factory = self
x = GmailOAuthAuthenticator(self.reactor)
p.registerAuthenticator(x)
return p
第 8 步 - 使用访问 token 进行身份验证
不要使用“登录”,而是获取访问 token (如有必要),然后使用身份验证。
更改问题中的示例代码:
@defer.inlineCallbacks
def serverGreeting(self, caps):
# log in
try:
# the line below no longer works for gmail
# yield self.login(mailuser, mailpass)
if GmailOAuthAuthenticator.authName in self.authenticators:
yield self.authenticators[AriGmailOAuthAuthenticator.authName].getToken()
yield self.authenticate("")
try:
yield self.uponAuthentication()
except Exception as e:
uponFail(e, "uponAuthentication")
except Exception as e:
uponFail(e, "logging in")
关于python - 如何使用Twisted查看OAuth2.0认证的Gmail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29712644/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t