OAuth2:RuntimeError:刷新令牌不可用

问题描述

我使用OAuth2 :: Client获取access_token。 需要使用refresh_token刷新它

client_id = '95585XXXXXXXoogleercontent.com'
secret_key = 'R10Ze490IYa'
client = OAuth2::Client.new(client_id,secret_key,{
  authorize_url: 'https://accounts.google.com/o/oauth2/auth',token_url: 'https://accounts.google.com/o/oauth2/token'
})


redirect_url = client.auth_code.authorize_url({
  scope: 'https://www.googleapis.com/auth/analytics.readonly',redirect_uri: 'https://example.com',access_type: 'offline'
})

auth_code = '4/5AF6VI0JMcmA38XXXXX' # getted from redirect_url clicking 

access_token = client.auth_code.get_token(auth_code,redirect_uri: 'https://example.com')

然后我尝试刷新令牌:

access_token.refresh!

我有错误

运行时错误:refresh_token不可用

解决方法

需要添加-提示:“同意”:

  redirect_url = client.auth_code.authorize_url({
    scope: 'https://www.googleapis.com/auth/analytics.readonly',redirect_uri: 'https://example.com',access_type: 'offline',prompt: 'consent'
  })

然后您可以获得新的access_token:

new_access_token = access_token.refresh!

您还可以使用以下方法保存令牌以供将来使用:

hash = access_token.to_hash  # save it
# load:
loaded_token = OAuth2::AccessToken.from_hash(client,hash)