【问题标题】:Generating SASL XOAUTH2 client response for Gmail IMAP access using Ruby使用 Ruby 为 Gmail IMAP 访问生成 SASL XOAUTH2 客户端响应
【发布时间】:2013-06-01 12:06:36
【问题描述】:

我正在尝试使用 Ruby 中的 XOAUTH2 通过 IMAP 访问我的 Gmail 电子邮件。

通过使用 OAuth 2.0 和 oauth2 gem 进行身份验证,我已成功生成访问令牌(和刷新令牌)。我将使用gmail_xoauth 通过 IMAP 访问 Gmail。所以我现在需要根据the Gmail XOAuth2 docs 生成 SASL 初始客户端响应:

The SASL XOAUTH2 initial client response has the following format:  

    base64("user=" {User} "^Aauth=Bearer " {Access Token} "^A^A")

using the base64 encoding mechanism defined in RFC 4648.
^A represents a Control+A (\001).

我不清楚我如何在我的字符串中表示“Control+A”。我只是使用^A吗?

key = Base64.encode64("user=#{email}^Aauth=Bearer #{access_token_obj.token}^A^A")

This python script 使用\1 代替^A。我也试过\001。无论我尝试什么,在验证(在 irb 中)时,我得到的结果是:

>> imap = Net::IMAP.new('imap.gmail.com', 993, usessl=true, certs=nil, verify=false)
>> imap.authenticate('XOAUTH2', email, key)
OpenSSL::SSL::SSLError: SSL_write:: bad write retry

该错误可能完全不相关,但我不确定我尝试过的任何选项都是正确的。

【问题讨论】:

  • 看来您完全无法连接到服务器。
  • 啊,谢谢。虽然今天我收到了这个错误:Net::IMAP::NoResponseError: Invalid credentials (Failure)。我想这就是进步……

标签: ruby oauth gmail imap sasl


【解决方案1】:

终于想通了……我根本不需要做 Base64 编码步骤!

gmail_xoauth adds the XOAUTH authenticatorNet::IMAP 本身。我意识到这只需要来自 Google 的未编码 access_token,而不是更长的 Base64 编码字符串。

所以,如果:

email = `fredbloggstest@gmail.com`
# The result of the OAuth2 dance (as well as a refresh_token):
access_token = 'ya13.AHES6Y3F54_5fAoz_8VuG-7pzQAo3R0_ukt7dhfgRnJh41Q'

那么我不必对任何内容进行 Base64 编码。我只是这样做:

imap = Net::IMAP.new('imap.gmail.com', 993, usessl=true, certs=nil, verify=false)
imap.authenticate('XOAUTH2', email, access_token)

我回来了:

#<struct Net::IMAP::TaggedResponse tag="RUBY0001", name="OK", data=#<struct Net::IMAP::ResponseText code=nil, text="fredbloggstest@gmail.com Fred Bloggs authenticated (Success)">, raw_data="RUBY0001 OK fredbloggstest@gmail.com Fred Bloggs authenticated (Success)\r\n">

(作为奖励,this is a handy Ruby script 从 OAuth 舞蹈中获得 access_token。)

【讨论】:

  • 如果我没有被 Google 自己的文档分心,我会看到 gmail_xoauth 的自述文件描述了如何做到这一点。白痴。
  • 这还能用吗?我在这里遇到错误:stackoverflow.com/questions/31443926/…
猜你喜欢
  • 2014-07-04
  • 2017-12-15
  • 1970-01-01
  • 1970-01-01
  • 2016-07-31
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多