首页 > 解决方案 > 获取无法刷新 google_oauth2 身份验证令牌错误。

问题描述

我正在尝试从 OAuth.io 为任何基于 Google 的提供商获取访问令牌,但是每当我进行身份验证时,我都会获得 access_token 但没有 refresh_token。我为 access_type 选择了离线,但仍然没有乐趣。

    def google_auth
        # Create a new API client & load the Google Drive API
        client = Google::APIClient.new
        client.authorization.client_id = ENV['GOOGLE_ID']
        client.authorization.client_secret = ENV['GOOGLE_SECRET']
        client.authorization.scope = ENV['GOOGLE_SCOPE']
        client.authorization.redirect_uri = ENV['REDIRECT_URI']
        client.authorization.code = self.code.chomp || ""
        client.authorization.access_token = self.token
        client.authorization.refresh_token = self.refresh_token
      #  client.authorization.additional_parameters = {
      #  "access_type" => "offline",         # offline access
      #  "include_granted_scopes" => "true"  # incremental auth
      #


        if client.authorization.refresh_token &&
            client.authorization.expired?
            client.authorization.fetch_access_token!
         end
        return client
      end

      def refresh_google
        options = {
          body: {
            client_id: ENV['GOOGLE_ID'],
            client_secret: ENV['GOOGLE_SECRET'],
            refresh_token: self.refresh_token,
            grant_type: 'refresh_token',
            access_type: 'offline'
          },
          headers: {
            'Content-Type' => 'application/x-www-form-urlencoded',
          #  'access_type' =>'offline'
          }
        }
        @response = HTTParty.post('https://accounts.google.com/o/oauth2/token', options)
        if @response.code == 200
          self.token = @response.parsed_response['access_token']
          self.save
        else
          Rails.logger.error("Unable to refresh google_oauth2 authentication token.")
          Rails.logger.error("Refresh token response body: #{@response.body}")
        end
      end

请在这方面提供帮助

标签: ruby-on-railsgoogle-apigoogle-oauth

解决方案


Issue resolved: I was trying to put 

"client.authorization.additional_parameters = {
        "access_type" => "offline",         # offline access
        "include_granted_scopes" => "true"  # incremental auth"
in User the rb model where callback was made but had to put it under session controller where API was called!

推荐阅读