Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

ruby on rails - How do I refresh my google_oauth2 access token using my refresh token?

I have a RoR app where I am authenticating against Google using omniauth and google_oauth2 where I am requesting offline access.

How do I use my refresh token to request a current access token? Also, how can I refresh my access token when it no longer works? I don't want to have any user interface in this situation, assuming of course that the authorization hasn't been taken away.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For an example using the Ruby HTTParty gem:

Where @auth is an ActiveRecord record that stores the auth keys for the specific user you are trying to refresh tokens for.

  # Refresh auth token from google_oauth2 and then requeue the job.
  options = {
    body: {
      client_id: <YOUR GOOGLE API CLIENT ID HERE>,
      client_secret: <YOUR GOOGLE API SECRET KEY HERE>,
      refresh_token: @auth.refresh_token,
      grant_type: 'refresh_token'
    },
    headers: {
      'Content-Type' => 'application/x-www-form-urlencoded'
    }
  }
  @response = HTTParty.post('https://accounts.google.com/o/oauth2/token', options)
  if @response.code == 200
    @auth.token = @response.parsed_response['access_token']
    @auth.expires_in = DateTime.now + @response.parsed_response['expires_in'].seconds
    @auth.save        
  else
    Rails.logger.error("Unable to refresh google_oauth2 authentication token.")
    Rails.logger.error("Refresh token response body: #{@response.body}")
  end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...