Google API access_type离线无法使用Rails

时间:2016-06-17 03:31:24

标签: ruby-on-rails google-api gmail-api

我正在使用gem' google-api-client',' 0.9' 我无法使用离线访问获取刷新令牌。我有两个问题: 1.为什么我不能让它工作: 启动授权请求的控制器是show action:

def show
  @user = User.find(params[:id])
  @login_url = get_gmail_authorize_url
  if session.has_key?(:access_token)
    @user.update_attributes(
      gmail_access_token: session[:access_token]
      )
  end
end

我在帮助文件中创建了一个方法来获取授权URL:

def get_gmail_authorize_url
  client_secrets = Google::APIClient::ClientSecrets.load(... path)
  auth_client = client_secrets.to_authorization
  auth_client.update!(
    scope: 'https://www.googleapis.com/auth/gmail.compose',
    redirect_uri: 'http://localhost:3001/authorize',
    :additional_parameters => {"access_type" => "offline", "approval_prompt" => "force"}
  )
  login_url = auth_client.authorization_uri.to_s
end

但是,当我点击链接时,它会重定向到gmail,要求获得“管理草稿和发送电子邮件”的许可。但不要离线访问。然后,不会随代码传递刷新令牌。

对于我的回调操作:

def gettoken
  client_secrets = Google::APIClient::ClientSecrets.load(... path)
  auth_client = client_secrets.to_authorization
  auth_client.update!(
    scope: 'https://www.googleapis.com/auth/gmail.compose',
    redirect_uri: 'http://localhost:3001/authorize'
  )
  if request['code'] == nil
    auth_uri = auth_client.authorization_uri.to_s
    redirect_to auth_uri
  else
    auth_client.code = request['code']
    response = auth_client.fetch_access_token!
    session[:access_token] = response['access_token']
    redirect_to user_path(id: session[:user_id])
  end
end

当我添加此内容时:

auth_client.update!(
  ...
  :additional_parameters => {"access_type" => "offline", "approval_prompt" => "force"}
)

到gettoken操作,我在gettoken中允许应用程序后得到Authorization failed. Server message: { "error" : "invalid_request", "error_description" : "Parameter not allowed for this message type: access_type" }:/

  1. 是不是创造了两个不同的OAuth :: Client有点多余?我知道重定向时对象不会被保存和丢失,但是没有办法保存它吗?
  2. 更新

    以下是授权对话框的屏幕截图。您可以在网址Google Authorization Dialog

    中看到access_type = offline

1 个答案:

答案 0 :(得分:0)

我通过在原始通话中更新为https://mail.google.com/来解决此问题。仍然不确定发生了什么,但现在我并不担心它。

auth_client.update!(
  scope: 'https://mail.google.com/',
  redirect_uri: 'http://localhost:3001/authorize',
  :additional_parameters => {
    "access_type" => "offline",
    "include_granted_scopes" => "true"
  }
)