Google API Ruby Client - single user with OAuth 2.

2019-09-01 04:01发布

问题:

the goal is to have one Google (YouTube) account for the web app. Users of the web app will be able to upload videos via this account to the one YouTube channel. After many hours im in the ends. I've found plenty of samples how to implement for Google user <-> web app interaction, but I don't need such comprehensive solution.

I'm trying over OAuth 2.0 (as recommended) and with Google API Ruby Client (https://github.com/google/google-api-ruby-client)

So far I have authorized the Google account (which will have that YouTube channel) with the web app, all necessary scopes included, offline access too and I have mechanism for refreshing access token. So I have access token, refresh token, client id and client secret.

But I don't know how to send a simple authorized request. The result below returns me "Daily Limit for Unauthenticated Use Exceeded." after a while so something wrong - i guess im missing part with client id and client secret.

So the question is: How to send simply authorized request via OAuth 2.0 with Google API Ruby Client, when we work with only one user and we have all necessary ids, secrets and tokens?

Thanks for any help or suggestion.

# Faraday connection
conn = Faraday.new(:url => 'https://accounts.google.com',:ssl => {:verify => false}) do |faraday|
  faraday.request  :url_encoded
  faraday.response :logger
  faraday.adapter  Faraday.default_adapter
end    

# Refresh token
result = conn.post '/o/oauth2/token', {
  'refresh_token' => "1/1lDIvifN******************dk9Akuc9ELVKM0",
  'client_id' => "61********506.apps.googleusercontent.com",
  'client_secret' => "********************g_dLfKmi",
  'grant_type' => 'refresh_token'}

@output = ActiveSupport::JSON.decode result.body
@access_token = @output['access_token']   
@token_type = @output['token_type'] 


# Google Client
client = Google::APIClient.new      

# YouTube API v3
api = client.discovered_api('youtube', 'v3')

# Retrieve list of playlists (not working)
@result = client.execute(
  :api_method => api.playlists.list,
  :parameters => {'part' => 'snippet', 'mine' => 'true'},
  :authorization => {'token_type' => @token_type, 'access_token' => @access_token}
)

回答1:

Ok, so I though the :authorization param in the execute request will add HTTP header Authorization: token_type access_token itself, but not and it was a problem.

So this works:

@result = client.execute(
  :api_method => api.playlists.list,
  :parameters => {'part' => 'snippet', 'mine' => 'true'},
  :authorization => {:token_type => @token_type, :access_token => @access_token},
  :headers => {:authorization => @token_type + ' ' + @access_token}
)