使用lib google-drive-ruby获取Refresh Token

时间:2018-04-09 12:24:23

标签: ruby google-auth-library-ruby

来自文章:https://github.com/gimite/google-drive-ruby/blob/master/doc/authorization.md

代码:

public function getAc($eventId) {
    // Pull event
    $event = $this->eventService->api->getEventForce($eventId);

    // If no access code for the event, generate one and update event record accordingly
    if ($event->access_code == null) {

        $access_code = $this->generateAccessCode();
        DB::update('update events set access_code = ? where id = ?', [$access_code, $eventId]);

        // Load updated event from DB.
        $event = $this->eventService->api->getEventForce($eventId);
    }

    // Is the event currently private? return access code
    if ($event->privacy=='private') {
        return $event->access_code; // HERE: value comes back from the API but on MySQL Workbench it's still null.
    }

    // Is it public ? return empty string.
    else {
        return '';
    }
}

然后

如果您想在之后恢复会话,可以在credentials.fetch_access_token之后存储credentials.refresh_token!

但在credentials.fetch_access_token之后! credentials.refresh_token是nil

我如何获得refresh_token? 或者下次将凭据保存到数据库?

1 个答案:

答案 0 :(得分:1)

需要添加additional_parameters:

require "googleauth"

credentials = Google::Auth::UserRefreshCredentials.new(
  client_id: "YOUR CLIENT ID",
  client_secret: "YOUR CLIENT SECRET",
  scope: [
    "https://www.googleapis.com/auth/drive",
    "https://spreadsheets.google.com/feeds/",
  ],
  redirect_uri: "http://example.com/redirect",
  :additional_parameters => {
         "access_type"=>"offline",
         "include_granted_scopes"=>"true",
         "prompt" => "consent"
  }
)
auth_url = credentials.authorization_uri

credentials.code = authorization_code
credentials.fetch_access_token!

然后得到:

refresh_token = credentials.refresh_token 

然后refresh_token可以存储在数据库中并在以后使用:

credentials.refresh_token = refresh_token
credentials.fetch_access_token!
session = GoogleDrive::Session.from_credentials(credentials)