Skip to content

Refresh access token using long lived refresh token #131

@rohitbegani

Description

@rohitbegani

I am trying to figure out how to update the access token using the refresh token which I got during the initial authorization. I tried multiple ways to do this but I always receive:

Signet::AuthorizationError: Authorization failed.  Server message:
{
  "error": "invalid_grant",
  "error_description": "Bad Request"
}

The main method to which I have been adding changes to is:

def refresh_google_calendar
  @service = Google::Apis::CalendarV3::CalendarService.new
  @service.authorization = google_secret

  # Attempts to refresh access token if already expired.
  @service.authorization.refresh! if @user.google_expires_at < Time.current
end

def google_secret
  Signet::OAuth2::Client.new(refresh_options)
end

def refresh_options
    { token_credential_uri: 'https://oauth2.googleapis.com/token',
      access_token: @user.google_token,
      expires_at: @user.google_expires_at,
      refresh_token: @user.google_refresh_token,
      client_id: ENV.fetch('GOOGLE_CLIENT_ID'),
      client_secret: ENV.fetch('GOOGLE_CLIENT_SECRET') }
  end

I tried another variation of the refresh_options as:

def refresh_options
  { refresh_token: @user.google_refresh_token,
      token_credential_uri: 'https://oauth2.googleapis.com/token',
      client_id: ENV.fetch('GOOGLE_CLIENT_ID'),
      client_secret: ENV.fetch('GOOGLE_CLIENT_SECRET') }
end

Also attempted using Google::Auth::UserRefreshCredentials as explained here but I still get the invalid_grant error.

I do know that my Client ID and Client Secret work because I use the same for the initial authorization request.

I would appreciate any help in figuring this out.

@sqrrrl @blowmage

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: questionRequest for information or clarification. Not an issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions