带有OAuth2的YouTube API v3:更新和删除失败并显示"权限不足"错误

Gla*_*eep 6 ruby youtube api youtube-api google-api-ruby-client

我想updatedelete使用视频的YouTube的API V3使用的OAuth2认证通过google-api-client (0.6.4)红宝石的宝石.但是,当我尝试执行这两个操作中的任何一个时,我看到以下错误消息:

Google::APIClient::ClientError: Insufficient Permission
Run Code Online (Sandbox Code Playgroud)

下面是奇怪的事情:使用完全相同的认证过程与updatedelete,我可以insert(上载)成功,没问题!所以,我不认为这是我的身份验证设置的问题,但我的代码中的其他地方.

scope在任何这些操作中,我的读写总是相同的:

https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.upload
Run Code Online (Sandbox Code Playgroud)

并根据API文档,该空间分隔组作用域应包括insert,updatedelete行动.

client_id,client_secret,refresh_token始终是所有这些行动也一样-所以,这不能成为问题,或者,可以吗?请注意,我的程序access_token在到期时会自动获取新内容,因此,我不相信这就是问题所在.

为了比较,这是我的insert(上传)代码的样子(这是有效的):

# Auth stuff, then...
@client.execute!(
  :api_method => @youtube.videos.insert,
  :body_object => body,
  :media => Google::APIClient::UploadIO.new(file_path, 'video/*'),
  :parameters => {
    'uploadType' => 'multipart',
    :part => body.keys.join(','),
  }
)
Run Code Online (Sandbox Code Playgroud)

这是我的delete代码看起来像(这失败):

# Auth stuff, then...
@client.execute!(
  :api_method => @youtube.videos.delete,
  :parameters => {
    'id' => youtube_id,
  }
)
Run Code Online (Sandbox Code Playgroud)

我错过了什么?不幸的是,用于删除YouTube API文档没有提供任何示例,因此我没有什么可比较的.如果有进一步的信息我可以提供更清楚的问题,请告诉我.

Gla*_*eep 13

我很确定这个问题的所有11个观点(截至本文撰写时)都是我,但我会发布一个答案,以防万一它在将来帮助某人:

我的代码本身没有问题.问题是我最初refresh_token为此帐户创建了我的帐户.

对于不熟悉的人来说,YouTube数据API(v3)不支持"服务帐户",这在Google API生态系统的其他地方通常是您唯一的客户自己设置OAuth2身份验证客户端的方式.解决方法是您必须手动完成的.采取以下步骤:


首先,转到Google"API控制台".在"API Access"下,您需要为"已安装的应用程序"创建"客户端ID".这将给你一个Client ID,一个Client secret和一个Redirect URI(你会想要非localhost一个).把它们写下来.

接下来,您需要通过在您喜欢的Web浏览器中访问如下所示的URL 来手动获取授权代码,同时登录到刚创建客户端ID的同一帐户:

https://accounts.google.com/o/oauth2/auth
  ?client_id={client_id}
  &redirect_uri={redirect_uri}
  &scope={space separated scopes}
  &response_type=code
  &access_type=offline
Run Code Online (Sandbox Code Playgroud)

当然,你需要输入client_id,redirect_uriscope查询参数.就我而言,这是我出错的地方.当我做这个手动步骤时,我应该把这个scope参数放在:

https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.upload
Run Code Online (Sandbox Code Playgroud)

但我只是做了https://www.googleapis.com/auth/youtube.upload,这不足以更新/删除视频!

最后,你需要获取一个refresh_token,通过这样的URL:

https://accounts.google.com/o/oauth2/token
  ?code={authorization_code}
  &client_id={client_id}
  &client_secret={client_secret}
  &redirect_uri={redirect_uri}
  &grant_type=authorization_code
Run Code Online (Sandbox Code Playgroud)

用以下命令卷曲它:

$ curl https://accounts.google.com/o/oauth2/token -d "code=..."
Run Code Online (Sandbox Code Playgroud)

这将返回包含您的JSON响应,refresh_token然后您在通过Google API以编程方式授权您的请求时使用该响应.